【问题标题】:Does calling multiple times save() method of hibernate with same object insert new record in DB?使用同一对象调用休眠的多次 save() 方法是否会在数据库中插入新记录?
【发布时间】:2020-02-27 05:14:38
【问题描述】:
for(int index=0; index<10; index++) {
   Session session = hibernateTemplate.getSessionFactory().openSession();
   session.save(object);
}

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

【问题讨论】:

  • 你可以自己试试,只记录sql语句。
  • 直接查数据库看看保存了多少对象&用logger查看sql语句日志

标签: java spring hibernate rest nhibernate-mapping


【解决方案1】:

这取决于对象的状态。

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

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

【讨论】:

    【解决方案2】:
     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.
    

    【讨论】:

      猜你喜欢
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多