[英]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);
}
此代码是否将传递的对象存储在 DB 中的 save(object) 中 10 次,还是每次都会被覆盖?
这取决于对象的状态。
如果每次都创建一个新对象,则新对象处于瞬态:它不映射到数据库记录,也不由任何持久化上下文管理。 因此,调用 Hibernate 的save()
方法将在数据库中创建一个新记录。
但是,如果您使用已附加到当前持久性上下文并映射到数据库记录的托管对象调用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*
综上所述,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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.