Vita Rara: A Life Uncommon

JBoss 4, JPA, @PrePersist and Primary Key Generation


Categories: | |

JBoss 4, JPA, @PrePersist and Primary Key Generation

In a past project I started using globally unique ID's (GUID) using XDoclet. I really like this methodology and planned on using it in Quadran.

So, I wrote my classes and was generating the ID's in the persist method of my data access objects (DAO). This didn't work very well, because when my persist would cascade the dependent objects did not have their ID's set, and Hibernate, which is JBoss uses to implement JPA, would throw an exception.

So, to work around this I started traversing the graph of objects in my business classes and setting the ID's before I handed them to the DAO's to be persisted. This was ugly, so I went in search of a better solution.

The obvious solution to me was to hook into the life cycle methods. From my past working with EJB2 I suspected that JPA would have life cycle methods, and I would likely be able to intercept the persist method, set the ID, then let JPA do its magic.

JPA does provide a method to hook into the persist() method on EntityManager. You can label any method on your bean with @PrePersist, which method will be called prior to the EntityManager persisting your bean. This seemed like the logical place to generate the ID and set it on the entity. Unfortunately this didn't work because Hibernate was validating that the ID was not null prior to calling the @PrePersist method.

Some investigation into this behavior turned up a JIRA entry on both the Hibernate and JBoss sites, along with a patch to address the issue.

After some manual work, I applied the patch to hibernate-entitymanager-3.2.0.RC2. (patch) After applying the patch the methods works great. Now the issue is seeing if the Hibernate or JBoss guys will apply the patch, or come up with a different solution that allows for this use of @PrePersist.