hibernate 之 merge() 步骤详解

hibernate 之 merge() 方法详解
hibernate中,是不允许出现同一主键对象有两个不同session同时关联的情况,如果出现这种情况hibernate会抛出"org.springframework.orm.hibernate3.HibernateSystemException: Illegal attempt to associate a collection with two open sessions; nested exception is org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions"这个异常,这个时候怎么办呢?我们需要通过hibernate提供的merge()这个方法来解决这一问题。

方法原型:
public Object merge(Object object)
使用merge方法是有如下情况
1、如果session中并不存在于参数object具有相同主见的对象,那么,首先需要根据主键从数据库中加载出该对象,然后将参数object中的属性拷贝到加载出来的那个对象上面,最后返回该持久化对象,同时需要注意,参数object并没有关联到session上。

2、如果session中存在与参数objcet具有相同主键属性的对象,那么直接将参数object中的属性拷贝到该持久化对象上,然后将该持久化对象返回,同时需要注意,参数object并没有关联到session上。