java – JPA / Hibernate preUpdate不更新父对象

在我的应用中,我定义了以下类:

@Entity
@Table(name = "forums")
public class Forum {
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    private String name;
    private Date lastActivity;

    @OneToMany(mappedBy = "forum", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE })
    private List<Post> posts;
@Entity
@Table(name = "posts")
public class Post {
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    private String username;
    private String content;
    private Date creationDate;

    @ManyToOne(optional = false, cascade = { CascadeType.MERGE, CascadeType.PERSIST })
    private Forum forum;

    public Post() {
        creationDate = new Date();
    }

    @PrePersist
    private void onPersist() {
        System.out.println(getClass().getName() + ": onPersist");
        if (creationDate == null) {
            creationDate = new Date();
        }

        forum.setLastActivity(creationDate);
    }

    @PreUpdate
    private void onUpdate() {
        forum.setLastActivity(new Date());
    }

如果我尝试向论坛实体添加新帖子,则可以通过@PrePersist回调在数据库中正确更新lastActivity字段.
但是,如果我尝试使用以下代码更新post实体:

  entityManager.getTransaction().begin();
  Post post = entityManager.find(Post.class, "postId");
  post.setContent("New post text");
  entityManager.merge(post);
  entityManager.getTransaction().commit();

只更新发布数据,并且lastActivity字段值不会更改.在我看来,@ PreUpdate方法应该做的伎俩和更新论坛实体.
这是一个错误还是我错过了什么?

最佳答案
这不是错误,即使通过快速尝试,这对我的预期方式起作用.负面消息是,由于以下原因,它不能保证有效:

从JPA 2.0规范中的第93页开始:

In general, the lifecycle method of a portable application should not
invoke EntityManager or Query operations, access other entity
instances, or modify relationships within the same persistence
context.[43] A lifecycle callback method may modify the
non-relationship state of the entity on which it is invoked.

和第95页:

It is implementation-dependent as to whether callback methods are
invoked before or after the cascading of the lifecycle events to
related entities. Applications should not depend on this ordering.

转载注明原文:java – JPA / Hibernate preUpdate不更新父对象 - 代码日志