简体   繁体   English

使用相同的对象多次调用休眠的 save() 方法会在数据库中插入新记录吗?

[英]Does calling multiple times save() method of hibernate with same object insert new record in DB?

for(int index=0; index<10; index++) {
   Session session = hibernateTemplate.getSessionFactory().openSession();
   session.save(object);
}

Does this code store the passed object in save(object) in DB 10 times or it will be overridden every time?此代码是否将传递的对象存储在 DB 中的 save(object) 中 10 次,还是每次都会被覆盖?

It depends on the object's state.这取决于对象的状态。

If you create a new object each time, new object is in the transient state: it is not mapped to a database record and not managed by any persistence context.如果每次都创建一个新对象,则新对象处于瞬态:它不映射到数据库记录,也不由任何持久化上下文管理。 So, calling Hibernate's save() method will create a new record in the database.因此,调用 Hibernate 的save()方法将在数据库中创建一个新记录。

But if you call save() method with a managed object which is already attached to the current persistence context and mapped to a database record: the same object will be updated.但是,如果您使用已附加到当前持久性上下文并映射到数据库记录的托管对象调用save()方法:将更新相同的对象。

 save method in hibernate:
 *Persist the given transient instance, first assigning a generated identifier. (Or
 using the current value of the identifier property if the assigned
 generator is used.) This operation cascades to associated instances if the
 association is mapped with cascade="save-update"
 Accept parameters :@param object a transient instance of a persistent class
 Return Prameters : @return the generated identifier*

In summary, the save() method saves records into the database by INSERT SQL query, Generates a new identifier, and returns the Serializable identifier back.综上所述,save() 方法通过INSERT SQL 查询将记录保存到数据库中,生成新的标识符,并返回Serializable 标识符。 So you will have 10 Object record in your database with different Ids因此,您的数据库中将有 10 个具有不同 ID 的对象记录

 Read more: https://javarevisited.blogspot.com/2012/09/difference-hibernate-save-vs-persist-and-saveOrUpdate.html#ixzz6F8Hiy8fF

 Hope it helps.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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