java - 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 initial db table data is
category = maths
fee=1000
recommendedbook= maths magic
thought above code copy uncommon fields c1 c2, , override common fields of c2 c1. expected result
category = science
fee=3000
recommendedbook= modern history
copied entire c1 data c2 , updated db c1, , c2 data lost.actual result is
category = science
fee=3000
recommendedbook= maths magic
infact not merging, overriding. how expected result?
the behavior see expected. how hibernate know fields must merged , others must not? null valid values fields, , setting fields null merging them valid operation.
to achieve result, merge fields want 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()); } ...
Comments
Post a Comment