I am observing a behaviour of Hibernate used as JPA provider which I cannot understand. Could you please help?
I have to import external data into existing and possibly new persistent entities. The code I wrote does the following (in a transaction using a transaction-scoped entity manager):
(1) Try to find an existing entity using the business key (taken from the external data). (2) If no such entity exists, create one and call persist() on it. (My metaphor for perist() is: "mark for persisting".) (3) In both cases we now have a managed entity. Update it using external data.
At the end of the transaction the changes are flushed and committed by Hibernate JPA using SQL/JDBC.
Now the thing I do not understand reveals if you turn on tracing: In the case of a new entity, Hibernate generates for (2) and (3) two SQL statements:
INSERT for (2), UPDATE for (3).
But a new entity could be stored using only one INSERT statement at the end of the transaction, using the latest state of the entity object.
Why does it work not this way? Is there some rule in the JPA specification or is it just an implementation choice?
|