participate


Enterprise JavaBeans - URGENT! JPA - Retrieve autogenerated keys from MySQL
This question is not answered.

<<   Back to Forum  |   Give us Feedback
This topic has 3 replies on 1 page.
ParampreetDhatt
Posts:25
Registered: 2/19/07
URGENT! JPA - Retrieve autogenerated keys from MySQL   
Feb 14, 2008 2:45 AM
 
 
I'm persisting an Entity class to the database through the following code:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU");
EntityManager em = emf.createEntityManager();
 
em.getTransaction().begin();
em.persist(user); // user is the Entity class object
em.getTransaction().commit();


Now through JPA, how do I obtain the autogenerated keys generated by the query above?

Any help or pointers will be appreciated.
 
Jamesssss
Posts:88
Registered: 2/11/08
Re: URGENT! JPA - Retrieve autogenerated keys from MySQL   
Feb 14, 2008 6:05 AM (reply 1 of 3)  (In reply to original post )
 
 
Assuming you have mapped your @Id in your entity with @GeneratedValue(strategy=IDENTITY) and created your table with AUTO_INCREMENT on the primary key column, then the id should be assigned to your object on commit.

So you can access the id from your object after the commit call. If you need it before the commit, you can call flush() to have the id assigned.

see also, http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Identity_sequencing

-- James : http://www.eclipselink.org
 
Dhaval.Yoganandi
Posts:380
Registered: 2/15/08
Re: URGENT! JPA - Retrieve autogenerated keys from MySQL   
Feb 14, 2008 8:56 PM (reply 2 of 3)  (In reply to original post )
 
 
hi,

you can try the following query (after insert query) in mysql to get last generated key..

select last_insert_id();


hope this will help u...

Edited by: Dhaval.Yoganandi on Feb 14, 2008 8:55 PM
 
Praveen_Soni
Posts:13
Registered: 10/11/07
Re: URGENT! JPA - Retrieve autogenerated keys from MySQL   
Mar 20, 2008 2:03 PM (reply 3 of 3)  (In reply to #1 )
 
 
Jamesssss's suggestion works fine. Thanks Jamesssss.
 
This topic has 3 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 23
  • Guests : 117

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums