java - Hibernate 始终使用 SaveOrUpdate 安全吗?

标签 java hibernate dao

我正在使用 Hibernate 4 并正在实现我的 DAO 和服务。看来我可以只实现 saveOrUpdate() 而不是分别实现 save()update() ,这需要服务检查是否应该调用 save()update()

1) Hibernate 在 saveOrUpdate() 中的未保存值检查是否已优化到足以始终调用它,还是我应该自己进行检查?

2) 如果保存或更新的决定取决于键以外的字段,saveOrUpdate() 是否无法使用?

最佳答案

1) 请参阅此处:Hibernate automatic state detection它说

saveOrUpdate() does the following:

-if the object is already persistent in this session, do nothing

-if another object associated with the session has the same identifier, throw an exception

-if the object has no identifier property, save() it

-if the object's identifier has the value assigned to a newly instantiated object, save() it

-if the object is versioned by a or , and the version property value is the same value assigned to a newly instantiated object, save() it

-otherwise update() the object

因此,在某些情况下,偶尔会执行一次 Select 来查看对象是否已存在(例如,如果 ID 不是某个自动生成的值)。因此,如果您手动执行此操作或让 hibernate 执行此操作,对我来说没有什么区别,如果有的话,我会说使用 saveOrUpdate 具有更好的性能,因为首先执行更多检查来排除更新,这可以节省某些插入的时间,其次,当您自己进行检查时,您必须在检查时使用完整的 hibernate select 遍历更多层。 另外:自己进行检查会对代码的可维护性产生影响。例如,如果您添加二级缓存,您可能需要优化您的保存和选择。或者,如果您应用一些其他调整,您可能需要在更多地方更改代码。

2) saveOrUpdate 仅考虑条目标识符。所以是的,它不能用于键以外的字段。

关于java - Hibernate 始终使用 SaveOrUpdate 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21557436/

相关文章:

java - @Autowired 不适用于从非 spring jpos 库实现的类

java - 文档中术语的出现频率

Java统计字符串中数字、特殊字符和字母的变化次数

java - MySQL 插入数据时出现错误 "Duplicate entry ' ' for key "

java - Spring DaoSupport 和@PersistanceContext EntityManager?

mysql - DAO OpendataBase(DSN 对话框始终打开)

java - @PropertySource @Value 静态字符串返回 null

java - hibernate查询缓存和时间戳

hibernate - 外键必须与多对一映射的引用主键具有相同的列数

php - 在 PHP 中创建 DAO 的正确方法