I need to implement Historization in the sense that we must have a new record for any updated record. All records have a deleted and inserted date. So what we do is set the deleted date to NOW when updating, and inserting a new record with insertion date NOW and deleted date NULL.
I am using JPA with eclipseLink as the persistent provider. My problem is that I need to do the "extra" insert when JPA think that it needs to update. So far I have set updatable=false on the Entity for non meta data fields. I update the insertionDate and deletionDate and the userName. Which all works as expected. All I now need to do is to make the extra insert.
I am trying to solve the issue using an entityListener, in which I implement @postUpdate and @preUpdate. I can't get it to work as I end up in a deadlock if I try to commit the new transaction that I do on @postUpdate. If I do not make a new EntityManager and a transaction, but mere call persist on the existing EntityManager nothing happens with the "new" entity for some reason.
Code below:
import java.util.Calendar;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.PreUpdate;
public class ColorEntityListener {
public ColorEntityListener()
{
}
@PreUpdate
void onPreUpdate(ColorEntity c)
{
System.out.println("onPreUpdate");
c.setDeletionDate(Calendar.getInstance());
}
@PostUpdate
void onPostUpdate(ColorEntity c)
{
System.out.println("onPostUpdate");
createNewRecord(c);
}
@PostPersist
void onPostPersist(ColorEntity c)
{
System.out.println("onPostPersist");
}
private void createNewRecord(ColorEntity c) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("v2_tl");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
ColorEntity cNew = new ColorEntity();
cNew.setPrNumber(c.getPrNumber());
cNew.setHs(c.getHs());
cNew.setCountryCode(c.getCountryCode());
cNew.setValidFrom(c.getValidFrom());
cNew.setValidUntil(c.getValidUntil());
cNew.setColorCode(c.getColorCode());
//cNew.setId(0);
cNew.setInsertDate(Calendar.getInstance());
cNew.setDeletionDate(null);
em.persist(cNew);
System.out.println("Before commit of new record");
em.getTransaction().commit();
System.out.println("After commit of new record");
}
}