是否可以在@ Pre/PostPersist Listener中保留新实体?

rhi*_*nds 10 java spring hibernate jpa

我正在尝试设置我的hibernate应用程序,以便Notification每次Activity创建实体时都持久保存新实体- 此时,我尝试的所有内容都Notification无法以静默方式存在(日志中没有错误但sql从未执行过).

任何人都可以确认甚至可以在Hibernate pre/postPersist监听器中保留其他实体吗?

我在文档中读到:

回调方法不能调用EntityManager或Query方法!

但我已经阅读了其他几个讨论线程,似乎表明它是可能的.

作为参考,我尝试的两种方法是:

  1. @PrePersist方法 - 在Activity和之间设置Notificationcascade.ALL 关系,并且在PrePersist方法中简单地创建一个新的Notification并将其链接到Activity正在创建的存在,希望Notification它将被保留.

  2. @PostPersist方法 - 使用@Configurable和一个ListenerClass,在服务中连接并创建一个新Notification实体,然后显式调用entityManger持久化

有人可以证实我的尝试是可能的吗?

Mr.*_*mes 2

为什么一定要坚持或者发挥Notification作用?以下代码应保留这两个实体:@PrePersist@PostPersist

@Entity
public class Activity implements Serializable {
   @OneToOne(cascade={CascadeType.PERSIST})
   private Notification notification;
}

@Entity
public class Notification implements Serializable { }

@Stateless
public class MrBean implements MrBeanInterface {
   @PersistenceContext()
   private EntityManager em;

   public void persistActivity() {
      Activity act = new Activity();
      act.setNotification(new Notification());
      em.persist(act);
   }
}
Run Code Online (Sandbox Code Playgroud)

更新:您可以尝试在活动的构造函数内创建链接,如下所示:

@Entity
public class Activity implements Serializable {
   @OneToOne(cascade={CascadeType.PERSIST})
   private Notification notification;

   public Activity() {
      this.notification = new Notification();
   }
}

@Entity
public class Notification implements Serializable { }

@Stateless
public class MrBean implements MrBeanInterface {
   @PersistenceContext()
   private EntityManager em;

   public void persistActivity() {
      Activity act = new Activity();
      em.persist(act);
   }
}
Run Code Online (Sandbox Code Playgroud)

需要注意的一件事是我认为你不能使用@PostPersist. 更准确地说,您必须在坚持之前链接Notification到才能工作。ActivityActivitycascade={CascadeType.PERSIST}