是否使用同一对象多次调用休眠的save()方法会在DB中插入新记录?

时间:2020-02-27 05:14:38

标签: java spring hibernate rest nhibernate-mapping

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

此代码是否将传递的对象存储在DB的save(object)中10次,否则每次都会被覆盖?

2 个答案:

答案 0 :(得分:2)

这取决于对象的状态。

如果每次都创建一个新对象,则新对象处于过渡状态:它不映射到数据库记录,也不由任何持久性上下文管理。因此,调用Hibernate的save()方法将在数据库中创建一条新记录。

但是,如果使用已附加到当前持久性上下文并映射到数据库记录的托管对象调用save()方法,则将更新同一对象。

答案 1 :(得分:0)

 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*

总而言之,save()方法通过INSERT SQL查询将记录保存到数据库中,生成一个新的标识符,然后将Serializable标识符返回。因此,您的数据库中将有10个具有不同ID的对象记录

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

 Hope it helps.