File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Object Relational Mapping and the fly likes JPA and transactions: how to get last inserted record ID without flushing objects to the DB? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "JPA and transactions: how to get last inserted record ID without flushing objects to the DB?" Watch "JPA and transactions: how to get last inserted record ID without flushing objects to the DB?" New topic
Author

JPA and transactions: how to get last inserted record ID without flushing objects to the DB?

Fabrizio Pia
Greenhorn

Joined: Apr 24, 2007
Posts: 10
Hello. Here the problem:
JPA and EntityManager is the environment.

Inside a transaction I want to save an Entity object. I do it with entityManager persist() method.
Now, inside the same transaction (and without any commit() command), I need to get the ID of the record related to the last object just inserted.
I need the last record ID because I want to write it in another table but inside the SAME transaction in order to handle the right IDs relations among tables.
I can't get the ID because any data hasn't been committed. The DB can't "see" data.
The way is to run the flush() method. But in such manner all the data are flushed to the DB.
I don't want to do that, because my transaction (in terms of ACID model) is not ended. More changes I need to do before closing the transaction.

How can I do this?
Follows a brief code example:



As you can see, I need to flush the data in order to get the ID. But in such way I need to open another transaction to manage other tables.
Can anyone help me?

Thank you
Fabrizio
James Sutherland
Ranch Hand

Joined: Oct 01, 2007
Posts: 553
Flush does not commit the transaction, you make changes after calling flush, and call flush multiple times.

But if you really want to pre-allocate ids, don't use IDENTITY sequencing, use TABLE or SEQUENCE. I would never recommend IDENTITY sequencing, it has poor performance, and does not allow the id to be assigned in persist().

TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
Fabrizio Pia
Greenhorn

Joined: Apr 24, 2007
Posts: 10
Thank you James.

Well, I'm working with MySQL and the engine is MYISAM. It seems that flush commits the transaction!! Mmmhhh... is this behavior right?
Now, I tried with InnoDB engine and flush works well. It does not commit data. That is what I was expecting.

Thank you
Fabrizio
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JPA and transactions: how to get last inserted record ID without flushing objects to the DB?