本文介绍了JPA @PostPersist用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method persistData() which persists an entity object. I have another method findData() which performs find() operation on the same entity class for the primary key value which was persisted. When I call the findData() in the @PostPersist of the entity class, I get a null pointer exception. This has raised a few questions in my mind:


  1. 为什么会产生空指针错误?

  2. @PostPersist在现实中的用途是什么?

  3. @Postpersist实际上是什么时候调用的?提交后,提交期间或提交之前?

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

Any further insights would also be appreciated. Please find the relevant code and stacktrace below:

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)

/ strong>:我使用JPA 1.0

推荐答案

要回答您的问题1:

(需要代码和stacktrace)

(need the code and the stacktrace)

回答你的问题2:

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

The @PostPersist indicate a JPA callback method. It allows you to trigger some code through the entity life-cycle events.

现实生活中的例子

假设您有一个User表格,并且您希望在每次新用户持久化时生成确认电子邮件:您可以使用 PostPersist 方法。

Assume you have a User table and you want to generate a confirmation email every time a new User is persisted: you can do it in a PostPersist method.

要回答您的问题3:

相关部分的规格是在blod。

The relevant part of specs are in blod.

-2.0 specs:

From JPA-2.0 specs:

这篇关于JPA @PostPersist用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:35