1

I am trying to update the Student class(student_class) column based on the studentid.
I am using EntityManager with Criteria to update the records.
The code is compiling successfully, but records are not getting updated in the database.

StudentEntity:

@Getter
@Setter
Class StudentEntity{
 @Id
 @Column(name = "student_id")
 private long studentId;

 @Column(name = "student_name")
 private String studentName;

 @Column(name = "student_class")
 private String studentClass;
}

Logic to update Student class column

@Repository
pubilc class StudentRepository {

@PersistenceContext
EntityManager entityManager;

@Transactional
public void update(List < StidentEntity > studentList) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaUpdate < StudentEntity > criteriaUpdate = cb.createCriteriaUpdate(StudentEntity.class);
    Root < StudentEntity > root = creiteriaUpdate.from(StudentEntity.class);

    studentList.forEach(request - > {
            List < Predicate > predicates = buildWhereClase(cb, root, request);
            criteriaUpdate.where(predicates.toArray(new Predicate[] {}));
            formUpdateQuery(criteriaUpdate, root, request);
            int res = entityManager.createQuery(criteriaUpdate).executeUpdate();
            System.out.println("Update status: " + res);
        }
    }

    private List < Predicate > buildWhereClasue(CruteriaBuilder builder, Root < StudentEntity > root, StudentEntity request) {
        List < Predicate > predicates = new ArrayList < > ();
        predicates.add(builder.equal(root.get("studentId"), request.getStudentId()));

        return predicates;
    }


    private void formUpdateQuery(CriteriaUpdate < StudentEntity > criteria, Root < StudentEntity > root, StudentEntity request) {
        criteria.set(root.get("studentClass", request.getStudentClass()));
    }
}

PleaseHiber help.
mayank bisht
  • 618
  • 3
  • 14
  • 43
  • Depending on your configuration of the entity manager, I think you are missing a commit. Use em.getTransaction().commit(). – Marcinek Nov 22 '20 at 08:54
  • Marcinek- I am using @Transactional annotation. That will take care of the transaction lifecycle. – mayank bisht Nov 22 '20 at 09:41
  • Hence it does not update your entities in the database. Thus there is missing something. I'm not quite familiar with the CriteriaBuilder and using the EM on my own. Please make sure that @Transactional and EM are working fine together. – Marcinek Nov 22 '20 at 10:07
  • You use PersistenceContext EntityManager entityManager from one galaxy, and Transactional uses an entityManager from another galaxy. You can use https://github.com/KonopkoMikhail/TransactionMonitor to make sure of this. – Orthodox Nov 22 '20 at 11:16
  • can you enable hibernate show-sql and check if the query is really being executed ? – Shawrup Nov 22 '20 at 16:46
  • Shawrup- Yes, show-sql is enabled and I don't see any update query. – mayank bisht Nov 23 '20 at 06:09

0 Answers0