org.hibernate.Session.evict(Object object)方法的使用
2017-03-31 23:43
295 查看
在一个实体A、B的关联关系中,如下图:
B外键关联A,关联字段A_id
A中保存有B的集合blist
在A的实体属性blist,使用懒加载注解,如下:
@OneToMany(targetEntity=B.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="A_ID")
public List<B> getBlist() {
return blist;
}
操作(以下动作均处于某个事务管理中)
在service层读取到A后,假设A的某条记录a关联B的多条记录b1、b2,即a.blist = {b1, b2}
如果该读取操作处于事务中,则a不能通过setBlist(null)来将blist集合设置为空,否则在事务关闭时,数据将会同步到数据库中,使得B中的记录b1、b2的字段A_ID都将被设置为空。如果数据库中A_ID字段不允许为空,则代码会抛出异常。
此时可以通过方法org.hibernate.Session.evict(a)来让a脱离持久化状态,然后就可以调用setBlist(null)方法来将blist置为空,如下:
dao.getSession().evict(a);
a.setBlist(null);
B外键关联A,关联字段A_id
A中保存有B的集合blist
在A的实体属性blist,使用懒加载注解,如下:
@OneToMany(targetEntity=B.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="A_ID")
public List<B> getBlist() {
return blist;
}
操作(以下动作均处于某个事务管理中)
在service层读取到A后,假设A的某条记录a关联B的多条记录b1、b2,即a.blist = {b1, b2}
如果该读取操作处于事务中,则a不能通过setBlist(null)来将blist集合设置为空,否则在事务关闭时,数据将会同步到数据库中,使得B中的记录b1、b2的字段A_ID都将被设置为空。如果数据库中A_ID字段不允许为空,则代码会抛出异常。
此时可以通过方法org.hibernate.Session.evict(a)来让a脱离持久化状态,然后就可以调用setBlist(null)方法来将blist置为空,如下:
dao.getSession().evict(a);
a.setBlist(null);
相关文章推荐
- org.hibernate.TransientObjectException: The instance was not associated with this session解决方法
- org.hibernate.NonUniqueObjectException:org.hibernate.NonUniqueObjectException: a different obj异常解决方法
- org.hibernate.NonUniqueObjectException异常解决方法
- 使用saveOrUpdate方法时,若hibernate的session存在了两个具有相同id的不同实体,则会报错
- org.hibernate.NonUniqueObjectException的原因与解决方法
- org.hibernate.NonUniqueObjectException的原因与解决方法
- Hibernate 3种状态的区分和各种session方法的使用
- org.hibernate.NonUniqueObjectException解决方法
- Hibernate中的session.evict(object) session.clear()
- Hibernate 使用JUnit 测试出现java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
- 出现 org.hibernate.NonUniqueObjectException 错误的解决方法
- 打开session的方法和org.hibernate.HibernateException: No CurrentSessionContext configured! 异常
- SpringMVC 4.0集成Hibernate 4如何使用sessionFactory.getCurrentSession()方法
- Hibernate学习--- Session.evict()方法
- org.hibernate.NonUniqueObjectException: A different object with the same identifier解决方法
- org.hibernate.NonUniqueObjectException异常解决方法(1)
- hibernate 使用sessionfactory的getCurrentSession()方法发生异常
- 使用hibernate遇到 org.hibernate.PersistentObjectException: detached entity
- Hibernate Session中flush、clear、evict方法的区别
- org.hibernate.SessionException: Session is closed! 异常解决方法