EntityManager.createQuery().executeUpdate not updating the database

1.3k Views Asked by At

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.
0

There are 0 best solutions below