简体   繁体   English

Hibernate:将已分离的实例数据合并到持久实例中

[英]Hibernate : merge detatched instance data in to persistent instance

Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Course c1 = (Course) session.get(Course.class, 1);
tx.commit();
session.close();
c1.setCategory("science");
c1.setFee("3000");

//C1 became detached instance here

session = HibernateUtil.getSessionFactory().openSession(); 
tx = session.beginTransaction();
Course c2 = (Course) session.get(Course.class, 1);
c2.setCategory("social");
c2.setRecommendedBook("Modern History");
session.merge(c1);
tx.commit();
session.close();

Lets say my initial db table data is 可以说我的初始数据库表数据是
category = maths 类别=数学
fee=1000 费用= 1000
recommendedBook= Maths magic 荐书=数学魔术

I thought the above code would copy uncommon fields from C1 to C2, and override common fields of C2 with C1. 我以为上面的代码会将不常见的字段从C1复制到C2,并用C1覆盖C2的公共字段。 So expected result would be 所以预期的结果是
category = science 类别=科学
fee=3000 费用= 3000
recommendedBook= Modern History 荐书=现代史

But it simply copied entire C1 data into C2 and updated db with C1, and all my C2 data is lost.Actual Result is 但是它只是将整个C1数据复制到C2中并用C1更新了db,因此我的所有C2数据都丢失了。
category = science 类别=科学
fee=3000 费用= 3000
recommendedBook= Maths magic 荐书=数学魔术
So its infact not merging, but fully overriding. 因此,它的实际作用不是合并,而是完全覆盖。 How to get my expected result? 如何获得我的预期结果?

The behavior you see is expected. 您看到的行为是预期的。 How could Hibernate know that some fields must be merged and some others must not? Hibernate如何知道某些字段必须合并而另一些字段不能合并? null is a valid values for all fields, and setting fields to null by merging them is a perfectly valid operation. null是所有字段的有效值,并且通过合并将字段设置为null是完全有效的操作。

To achieve your result, merge the fields that you want to merge explicitely: 要获得结果,请合并要显式合并的字段:

 Course c2 = (Course) session.get(Course.class, 1);
 c2.setCategory("social");
 c2.setRecommendedBook("Modern History");
 if (c1.getCategory != null) {
     c2.setCategory(c1.getCategory());
 }
 if (c1.getRecommendedBook() != null) {
     c2.setRecommendedBook(c1.getRecommendedBook());
 }
 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM