gpt4 book ai didi

JPA @PostPersist 用法

转载 作者:行者123 更新时间:2023-12-02 08:15:23 25 4
gpt4 key购买 nike

我有一个持久化实体对象的方法 persistData() 。我有另一个方法 findData() ,它对同一实体类执行 find() 操作以获取持久的主键值。当我在实体类的@PostPersist中调用findData()时,出现空指针异常。这在我心中提出了几个问题:

  1. 为什么会出现空指针错误?
  2. @PostPersist在现实中有什么用?
  3. @Postpersist 何时真正被调用?提交之后、提交期间还是提交之前?

任何进一步的见解也将不胜感激。请在下面找到相关代码和堆栈跟踪:

public void persistData(){
EntityManagerFactory fac= Persistence.createEntityManagerFactory("test");
EntityManager man = fac.createEntityManager();

Employee e = new Employee();
e.setEmpId(500);
e.setEmpName("Emp5");
e.setSalary(5000);
man.getTransaction().begin();
man.persist(e);
man.getTransaction().commit();
man.close();

}



public void findData(){
EntityManagerFactory fac= Persistence.createEntityManagerFactory("test");
EntityManager man = fac.createEntityManager();

Employee e=man.find(Employee.class, 500);
System.out.println(e.getEmpName());
man.close();
}

@PostPersist
public void getData(){
new Service().findData();
}

堆栈跟踪(部分):

Exception in thread "main" javax.persistence.RollbackException: java.lang.NullPointerException
at oracle.toplink.essentials.internal.ejb.cmp3.transaction.base.EntityTransactionImpl.commit(EntityTransactionImpl.java:120)
at oracle.toplink.essentials.internal.ejb.cmp3.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:60)
at Service.persistData(Service.java:18)
at Service.main(Service.java:34)
Caused by: java.lang.NullPointerException
at Service.findData(Service.java:28)
at Employee.getData(Employee.java:33)

注意:我使用的是 JPA 1.0

最佳答案

回答你的问题1:

(需要代码和堆栈跟踪)

回答你的问题2:

@PostPersist 表示 JPA 回调方法。它允许您通过实体生命周期事件触发一些代码。

现实生活中的例子?

假设您有一个 User 表,并且您希望在每次保留新用户时生成一封确认电子邮件:您可以在 PostPersist 方法中执行此操作。

回答你的问题3:

规范的相关部分是血色的。

来自 JPA-2.0 规范:

The PostPersist and PostRemove callback methods are invoked for an entity after the entity has been made persistent or removed. These callbacks will also be invoked on all entities to which these operations are cascaded. The PostPersist and PostRemove methods will be invoked after the database insert and delete operations respectively. These database operations may occur directly after the persist, merge, or remove operations have been invoked or they may occur directly after a flush operation has occurred (which may be at the end of the transaction). Generated primary key values are available in the PostPersist method.

关于JPA @PostPersist 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15702288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com