Merge () method of Hibernate

Source: Internet
Author: User
Document directory
  • I have been familiar with hibernate for a long time. The company's projects have been using ibatis. I encountered a problem when I was working on an external project yesterday:

 

I have been familiar with hibernate for a long time. The company's projects have been using ibatis. I encountered a problem when I was working on an external project yesterday:

   laborPerson.setId(laborPersonId);   ...
   LaborPerson oldLaborPerson = (LaborPerson)getDao().getObjById(LaborPerson.class, laborPersonId);   laborPerson.setCreateTime(oldLaborPerson.getCreateTime());   laborPerson.setCreateUser(oldLaborPerson.getCreateUser());   laborPerson.setUnit(oldLaborPerson.getUnit());   oldLaborPerson = null;

SaveOrupdate: the error "a different object with the same identifier value was already associated with the session" is reported.

In fact, I only want to modify the fields such as the Creation Time of the original old data. My friend told me to retrieve the old data and set it one by one. There are dozens of fields, I think there seems to be a way to merge it in the past. I tried it in an article and I can update it normally. (I Don't Need To saveOrupdate. I can directly judge whether to insert or update it based on the laborPersonId, update with merge), hibernate continues to explore...

 

  if(StringUtil.isNotNullOrBlank(laborPersonId))  {      LaborPerson oldLaborPerson = (LaborPerson)getDao().getObjById(LaborPerson.class, laborPersonId);      laborPerson.setCreateTime(oldLaborPerson.getCreateTime());      laborPerson.setCreateUser(oldLaborPerson.getCreateUser());      ...          HibernateUtil.getSession().merge(laborPerson);   }   else 
   {      laborPerson.setCreateTime(new Date());      laborPerson.setCreateUser(curUser);      ...             HibernateUtil.getSession().save(laborPerson);   }

 

 

 

Original article: http://littie1987.iteye.com/blog/1039082

Merge () method of Hibernate HibernateSQL

The following describes the Hibernate merge method. I plan to follow the three States of the hibernate object lifecycle.

1: If the pojo object is in the Free State, the Free State means that the id value of this object is null. Hibernate checks whether an object exists in the Database instead of looking at other information about the object, but whether the ID exists in the database. If the ID is null, it does not exist. Therefore, when we call the merge method, the insert operation is executed directly. This is a bit like the saveorupdate () method. Read a piece of code:

Java code
  1. User user = new user ();
  2. // User. setid (4 );
  3. User. setusername ("heyuanling2 ");
  4. User. setage (23 );
  5. User. setsex ("W ");
  6. User. setpassword ("heyuanling ");
  7. Session session = This. getsession ();
  8. Transaction TR = session. begintransaction ();
  9. // User exituser = (User) session. get (User. class, new Integer (1 ));
  10. Session. merge (user );
  11. Tr. commit ();
User user = new user (); // user. setid (4); User. setusername ("heyuanling2"); User. setage (23); User. setsex ("W"); User. setpassword ("heyuanling"); Session session = This. getsession (); transaction TR = session. begintransaction (); // user exituser = (User) session. get (user. class, new INTEGER (1); Session. merge (User); tr. commit ();

 

Let's look at the hibernate SQL statement:

Java code
  1. Hibernate:
  2. Select
  3. Max (id)
  4. From
  5. User _
  6. Hibernate:
  7. Insert
  8. Into
  9. User _
  10. (Username, password, sex, age, birthday, other, id)
  11. Values
  12. (?, ?, ?, ?, ?, ?, ?)
Hibernate: Select max (ID) from user_hibernate: insert into user _ (username, password, sex, age, birthday, other, ID) values (?, ?, ?, ?, ?, ?, ?)

 

Ii. unmanageable: if we put the code above // user. the comment of setid (4); is removed, so it becomes the object of detachment (in fact, it is so simple from the free to the tube, not as evil as officially said ...). Here is the SQL printing on the console:

Java code
  1. Hibernate:
  2. Select
  3. User0 _. id as id4_0 _,
  4. User0 _. username as username4_0 _,
  5. User0 _. password as password4_0 _,
  6. User0 _. sex as sex4_0 _,
  7. User0 _. age as age4_0 _,
  8. User0 _. birthday as birthday4_0 _,
  9. User0 _. other as other4_0 _
  10. From
  11. User _ user0 _
  12. Where
  13. User0 _. id =?
Hibernate: Select user0 _. ID as id4_0 _, user0 _. username as username4_0 _, user0 _. password as password4_0 _, user0 _. sex as sex4_0 _, user0 _. age as age4_0 _, user0 _. birthday as birthday4_0 _, user0 _. other as other4_0 _ from user _ user0 _ Where user0 _. id =?

No. Because the ID is not empty, Hibernate will not insert any more. Because the information of this object is the same as that in the database, Hibernate only executes a SELECT statement and does not update it. If we change the field value slightly, the SQL statement printed on the console should also have an update statement. In this case, merge also has the same method as saveorupdate.

 

 

3. Persistence: better understanding of persistence. If we get a record from the database, the record will be in the persistent state. If we call merge again, Hibernate will first determine whether the record has been modified, and if there is no record, it will do nothing, update after modification. This is a bit like saveorupdate.

Java code
  1. Session session = this. getSession ();
  2. Transaction tr = session. beginTransaction ();
  3. User exituser = (User) session. get (User. class, new Integer (1 ));
  4. Exituser. setAge (11 );
  5. Session. merge (exituser );
  6. Tr. commit ();
  7. Session. close ();
Session session = This. getsession (); transaction TR = session. begintransaction (); User exituser = (User) session. get (user. class, new INTEGER (1); exituser. setage (11); Session. merge (exituser); tr. commit (); Session. close ();

Check the result in the console again:

Java code
  1. Hibernate:
  2. Select
  3. User0 _. ID as id4_0 _,
  4. User0 _. Username as username4_0 _,
  5. User0 _. Password as password4_0 _,
  6. User0 _. Sex as sex4_0 _,
  7. User0 _. Age as age4_0 _,
  8. User0 _. Birthday as birthday4_0 _,
  9. User0 _. Other as other4_0 _
  10. From
  11. User _ user0 _
  12. Where
  13. User0 _. id =?
  14. Hibernate:
  15. Update
  16. User _
  17. Set
  18. Username = ?,
  19. Password = ?,
  20. Sex = ?,
  21. Age = ?,
  22. Birthday = ?,
  23. Other =?
  24. Where
  25. Id =?
Hibernate: select user0 _. id as id4_0 _, user0 _. username as username4_0 _, user0 _. password as password4_0 _, user0 _. sex as sex4_0 _, user0 _. age as age4_0 _, user0 _. birthday as birthday4_0 _, user0 _. other as other4_0 _ from user _ user0 _ where user0 _. id =? Hibernate: update user _ set username = ?, Password = ?, Sex = ?, Age = ?, Birthday = ?, Other =? Where id =?

If the record is not modified, there will be no subsequent update statement.

 

So what is the difference between merge and saveorupdate? Read a piece of code:

Java code
  1. Session session = this. getSession ();
  2. Transaction tr = session. beginTransaction ();
  3. User exituser = (User) session. get (User. class, new Integer (1 ));
  4. Tr. commit ();
  5. Session. close ();
  6. Session = getSession ();
  7. Tr = session. beginTransaction ();
  8. User exituser2 = (User) session. get (User. class, new Integer (1 ));
  9. Session. update (exituser );
  10. Tr. commit ();
  11. Session. Close ();
Session session = this. getSession (); Transaction tr = session. beginTransaction (); User exituser = (User) session. get (User. class, new Integer (1); tr. commit (); session. close (); session = getSession (); tr = session. beginTransaction (); User exituser2 = (User) session. get (User. class, new Integer (1); session. update (exituser); tr. commit (); session. close ();

Running the above Code, Hibernate reported an error: a different object with the same Identifier value was already associated with the session. This means that two objects with the same identifiers are not allowed in the session cache. So what if I change update to merge? After changing to merge, everything is OK and runs normally. In fact, merge will merge the objects with the same identifiers before executing the update. The specific direction of the merge is to merge the objects with the same identifiers to exituser2.

 

Note: before execution, the merge method returns to the cache to check whether there is a corresponding record, that is, there is a SELECT statement. The purpose of executing the modify statement is to determine whether the object has been modified. Regardless of the update statement, an update statement is used directly.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.