Entity state and entity id value in JPA/Hibernate after rollback

后端 未结 2 1598
鱼传尺愫
鱼传尺愫 2021-01-13 17:00

What happens with Entities in session if I make rollback ? Do they get back to the state before transaction ? In particular do they get new ids ?

Example:

         


        
相关标签:
2条回答
  • 2021-01-13 18:00

    All managed entites will become detached.

    Unless you are using an extended persistence context, rolling back also ends the persistence context.

    (see OpenJPA docs: http://openjpa.apache.org/documentation.html)

    0 讨论(0)
  • 2021-01-13 18:01

    I will simply quote from the JPA implementation (3.3.2 Transaction Rollback):

    For both transaction-scoped and extended persistence contexts, transaction rollback causes all pre-exist-ing managed instances and removed instances[31] to become detached. The instances’ state will be the state of the instances at the point at which the transaction was rolled back. Transaction rollback typically causes the persistence context to be in an inconsistent state at the point of rollback. In particular, the state of version attributes and generated state (e.g., generated primary keys) may be inconsistent. Instances that were formerly managed by the persistence context (including new instances that were made persistent in that transaction) may therefore not be reusable in the same manner as other detached objects—for example, they may fail when passed to the merge operation.[32]

    This actually means, that it depends whether you have or not an ID right before calling em.rollback() (which depends on FlushMode & JPA implementation). If an ID was assigned, than the ID will remain set. If not, then you will have no ID.

    0 讨论(0)
提交回复
热议问题