我正在努力更新学生的班级( student_class
)基于 studentid
.
我正在使用 EntityManager
更新记录的标准。
代码已成功编译,但数据库中的记录未更新。
学生人数:
@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;
}
更新学生类列的逻辑
@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()));
}
}
请随便帮忙。
暂无答案!
目前还没有任何答案,快来回答吧!