简体   繁体   中英

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
recommendedBook= Maths magic

I thought the above code would copy uncommon fields from C1 to C2, and override common fields of C2 with C1. So expected result would be
category = science
fee=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
category = science
fee=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? null is a valid values for all fields, and setting fields to null by merging them is a perfectly valid operation.

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());
 }
 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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