Getting a generated key without commiting transaction in JPA

 Assuming you have set  a generated value of any type to your entity and that it is mapped to an auto-increment field, you can get the generated key in JPA.
 

Before, I try to commit the transaction just to get a generated key.

 EntityManager em = getEntityManager();

         em.getTransaction().begin();
         
         em.persist(fixedItem);
         
         em.getTransaction().commit();
         
         fixedItem = em.merge(fixedItem);

         //start another transaction, persist and then commit again
 

I would back then commit and then merge with the Session (EntityManager is Session in Hibernate) and then commit again. This defeats atomicity, I didn't know until now that to generate a primary you only need to flash the EntityManager.

 

em.flush();

//more actions here

em.commit();
 


Hmmm... Perhaps I'll be posting about NamedQueries next time. :)
Published 06-28-2007 8:17 PM by lamia