Hibernate合并

时间:2012-01-13 04:41:35

标签: java hibernate

我正在测试hibernate并将此查询提供给

transaction = session.beginTransaction();
city = new City("A");
city  = (City)session.merge(city);
city.setName("B");
transaction.commit();

我在命令行中收到了这些查询:

Hibernate: insert into CITY (name) values (?)
Hibernate: update CITY set name=? where CITY_ID=?

我使用merge not save,所以为什么hibernate正在更新我的对象,它不应该更新。是吗?这是什么错误?

3 个答案:

答案 0 :(得分:23)

我将尝试使用更具体的例子来解释。假设您有如下情况:

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User userA = (User)session.get(User.class, 1101);
transaction.commit();
session.close();
// Since session is closed, userA is detached.

session = sessionFactory.openSession();
transaction = session.beginTransaction();
User userB = (User)session.get(User.class, 1101);
//Now here,  userB represents the same persistent row as userA.
//When an attempt to reattach userA occurs, an exception is thrown
session.update(userA);
transaction.commit();
session.close();

尝试重新挂接Detached对象时,发生了异常。

Exception in thread "main" org.hibernate.NonUniqueObjectException: a   
different object with the same identifier value was already associated
with the session:

This is because Hibernate is enforcing that only a single instance of a Persistent    object exists in memory.

要解决上述问题,请使用merge(),如下所示:

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User userA = (User)session.get(User.class, 1101);
transaction.commit();
session.close();
//userA is now detached as session is closed.

session = sessionFactory.openSession();
transaction = session.beginTransaction();
User userB = (User)session.get(User.class, 1101);
User userC = (User)session.merge(userA);
if (userB == userC) {
  System.out.println("Reattched user is equal");
}
transaction.commit();
session.close();

答案 1 :(得分:4)

这是一个排序问题。其实不是问题。 Hibernate完全按照你的要求去做。正如@TejasArjun所说,merge是关于合并检测数据的。这是发生了什么:

...
city  = (City)session.merge(city); 
// No different to save(). Hibernate schedules an insert to the
// database to store the current record.

city.setName("B"); 
// The object is now flagged as dirty and needing to be saved. 
// Hiberate automatically tracks properties on objects and knows when they change.

transaction.commit(); 
// Hibernate sees that 'city' has been changed since it was saved, 
// so it schedules an update to store the new data.

答案 2 :(得分:0)

因为会话尚未关闭,并且在持久性条款city对象仍然附加到会话。因此,hibernate会话将监听该对象的任何更改,并调用适当的dml语句。