【问题标题】:PostUpdate hook is not working, while doing batch updatePostUpdate 挂钩不起作用,同时进行批量更新
【发布时间】:2020-07-28 08:37:39
【问题描述】:


我正在使用 JPA/Hibernate。

我正在进行批量更新:

代码片段:

@PersistenceContext
private EntityManage entityManager;

   ...
private int update(StudentEntity studentEntity){
 CriteriaBuilder builder = entityManager.getCriteriaBuilder();
 CriteriaUpdate<StudentEntity > criteria = builder.createCriteriaUpdate(StudentEntity.class);
 Root<StudentEntity> root = criteria.form(StudentEntity.class)
 setFields(criteria, root, studentEntity)
 criteria.where(builder.equal(root.get("studentId"), studentEntity.getStudentId()));
 return entityManager.createQuery(criteria).executeUpdate();
}

private setFields(CriteriaUpdate<StudentEntity> criteria,  Root<StudentEntity> root,StudentEntity  studentEntity){
 criteria.set(root.get("studentName"),studentEntity.getStudentName());

 ....
}


在执行上述代码时@PostUpdate钩子没有被调用,为什么?

@PostUpdate
private update (StudentEntity studentEntity){
  System.out.println("@PostUpdate called.");
}


【问题讨论】:

    标签: java spring-boot jpa spring-data-jpa spring-data


    【解决方案1】:

    来自 JPA 规范(第 3.5.3 节):

    PreUpdatePostUpdate 回调分别发生在对实体数据进行数据库更新操作之前和之后。

    即这些事件仅在使用实体生命周期加载实体、对其进行操作然后将状态刷新到数据库时才会触发。

    【讨论】:

    • 感谢您的回答,那么您认为我现在应该怎么做?
    • 显然取决于你的目标是什么。
    • 我想保留现有代码,也想调用@PostUpdate回调方法。
    • 如果您不想更改更新代码以使用 JPA 生命周期但仍想调用 @PostUpdate 回调,则必须自己调用回调。似乎很明显。当然问题是:你为什么坚持使用你刚学会的方法不起作用?
    • 目前,如果需要的话,我们不想改变现有的方法。您提到我必须自己调用回调。我该怎么做?
    猜你喜欢
    • 2022-12-30
    • 2022-09-27
    • 2016-07-14
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多