回滚后JPA / Hibernate中的实体状态和实体ID值 [英] Entity state and entity id value in JPA/Hibernate after rollback

查看:92
本文介绍了回滚后JPA / Hibernate中的实体状态和实体ID值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我进行回滚,会话中的实体会发生什么?交易前他们是否回到状态?例如:

 会话    .startTransaction(); 
实体e =新实体(); //e.id == null
session.save(e); //假设它没问题
session.rollback(); // e.id == ???

更新

我做了Hibernate 4测试。在测试后,实体已经成为一个新的ID。

解决方案

我将简单引用JPA实现(3.3.2事务回滚):


对于事务范围和扩展持久化上下文,
事务回滚将导致所有预先存在的受管实例和
移除的实例[31]成为分离。这些实例的状态将是
事务处于
回滚点时的状态。事务回滚通常会导致持久性
上下文在回滚点处于不一致状态。特别是,在
中,版本属性和生成状态(例如,生成的主键
)的状态可能不一致。以前由持久性上下文管理的
实例(包括在该事务中持久化的新实例
)因此可能不是以与其他分离对象相同的方式可重用的
,例如,
它们在传递到合并操作时可能会失败[32]

这实际上意味着它取决于您是否拥有或者在调用 em.rollback()(这取决于FlushMode和JPA实现)之前不是ID。如果分配了ID,则ID将保持设置。如果没有,那么你将没有身份证。


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:

session.startTransaction();
Entity e = new Entity(); //e.id == null
session.save (e);        //suppose it was ok
session.rollback();      // e.id == ???

Update:

I've made the Hibernate 4 test. After the test the entity has become a new id.

解决方案

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.

这篇关于回滚后JPA / Hibernate中的实体状态和实体ID值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆