简体   繁体   中英

Why is Hibernate Save updating the records?

In hibernate, session.save() is supposed to save the records.It generates "insert" queries. However, I have written below simple program to check this. I am observing the save() can also be used to update the records. It is generating "update" query. Isn't save() doing the same job as saveorupdate() in the below program ?

SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
Transaction trans = session.beginTransaction();

Vehicle veh = new Vehicle();
veh.setId(1);
veh.setModel("Veh_mod");
veh.setName("Veh_Name");

Serializable obj =  session.save(veh);  
veh.setModel("Veh_mod_change");

obj =  session.save(veh);

session.flush();
trans.commit();
session.close();

------------------------- in the console--------------------------------

Hibernate: /* insert com.anvesh.test.Vehicle */ insert into VEHICLE (NAME, MODEL, ID) values (?, ?, ?)

Hibernate: /* update com.anvesh.test.Vehicle */ update VEHICLE set NAME=?, MODEL=? where ID=?

After your first call to save() , object veh becomes an attached object (aka. persistent object state). Subsequently mutating that object with setModel() and committing the transaction would cause hibernate to fire an update even without calling save() a second time.

Here's an example for reference: http://www.dineshonjava.com/p/transient-persistent-and-detached.html#.VEfGCme8G7E

Or perhaps a short video tutorial: http://javabrains.koushik.org/tutorials/hibernate_run/Hibernate-Tutorial-22---Transient,-Persistent-and-Detached-Objects.html

save() can do an update, if id is set on the object it saves. Check out this thread for differences between various saving methods. To quote from an accepted answer

save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity.

When you first called session.save(veh), your object becomes associated with the session. Hibernate will then know that it needs to use an "UPDATE" query when you save the object again.

Try:

Vehicle veh1 = new Vehicle();
veh1.setId(1);
veh1.setModel("Veh_mod");
veh1.setName("Veh_Name");

Vehicle veh2 = new Vehicle();
veh2.setId(1);
veh2.setModel("Veh_mod");
veh2.setName("Veh_Name");

session1.save(veh1);
session2.save(veh2); // try changing this to session2.saveOrUpdate()

then you'll see the difference between session.save() and session.saveOrUpdate()

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