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:
- Why is it giving a null pointer error?
- What is the use of @PostPersist in reality?
- When is a @Postpersist actually called? After commit, during commit or before commit?
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();
}
Stack Trace ( Partial ):
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)
Note: I am using JPA 1.0