简体   繁体   中英

How to insert/save an object using Hibernate session.save() without updating the old record

I have a search.jsp page where I search & retrieve a record from Database. I have to duplicate this record and make modifications and save both records.

Ex:

 method1(){
  Response response=new Response();
  //To perform DB search
  response=delegate.requestSearch(//some request criteria);
  Types obj1=(Types) response.getBaseEntity();
  Types obj2=obj1;
  obj2.setPromaryKeyObject(//some unique value);
 }

In my DAO, save method:

session.save(obj1);
session.save(obj2);
transaction.commit(); // transaction

When the debug point commits transaction, I get one update query only. But I expect two insert queries.

But this works fine. This was an attempt but this is not what I want to do.

Types tempObj1 = new Types();    
tempObj1.setValue1(obj1.getValue1();
 // all values of the object should be set
session.save(tempObj1);
Types tempObj1 = new Types();    
tempObj2.setValue1(obj2.getValue1();
 // all values of the object should be set
session.save(tempObj2);
transaction.commit(); // transaction

In this case I trigger two insert queries.

I'm pretty sure that the mistake is in my hibernate method as I'm very new to Hibernate. This same code works fine when I was using JDBC and MySql queries.

It's all about ids. If object with given id exist in database it is updated. If no id is set then it is generated according to generation strategy and new record is inserted. Sometimes (depends on configuration) you must set the id explicitly.

Since you use MySQL i guess you use autoincrement column as id and IDENTITY generation strategy. What you probably need to do is to leave id as is for updated record and set id to null for the one you want to insert as new.

This is due the obj2 == obj1 . Try to obj2 = obj1.clone() ;

Hibernate internally keeps track of objects you have save() 'd. You did not really create a new instance with this code

  Types obj1=(Types) response.getBaseEntity();
  Types obj2=obj1;

so hibernate thinks you're saving the same object again with no data changed, so naturally it did nothing.

There are two ways to solve this:

  • Copy the data to a new instance and call save again. This is a bit like the second code fragment you had.
  • Use the merge() method which does not associate the argument with the session, so that each time you call merge(something) , an insert is generated. (This assumed you've cleared the id of something and disassociated it with the session first.)

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