This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Object Relational Mapping and the fly likes Best Practices for JPA Generated Keys Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Best Practices for JPA Generated Keys" Watch "Best Practices for JPA Generated Keys" New topic

Best Practices for JPA Generated Keys

Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 15950

I've been working with Apache OpenJPA and a lot of what I do involves tables with generated integer keyfields. One of the problems with them is that since they're only generated when the backing store object has been created, the actual identity of the record is only available by retrieving the generated key.

For brute-force batch, I've been doing this:

However, I'm trying to use Spring, and the Spring equivalent goes something like this:

The problem here is that Spring is wrapping the entire method as a transaction, so the record hasn't been committed until after the return and thus no key is retrievable from within the method.

I want the save() method to be totally self-contained, but I'd rather not have to make it work by writing manual transaction code if I can avoid it.

Does anyone know a nice clean solution?

Customer surveys are for companies who didn't pay proper attention to begin with.
I agree. Here's the link:
subject: Best Practices for JPA Generated Keys
Similar Threads
Annonymous Inner class doesnt use final var
Error in Running Servlet from Client Side
How I can get the primary key assigned to an object when I use em.persist method?
Tweaking tomcat 6 file
Hibernate and Struts 2 question