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?
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().
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.