我发现JPA不支持以下更新操作:
Update Person p set p.name = :name_1 where p.id = :id_1,
p.name = :name_2 where p.id = :id_2,
p.name = :name_3 where p.id = :id_3
....
// It could go on, depending on the size of the input. Could be in 100s
所以我有两个选择:
选择1:
Query q = em.createQuery("Update Person p set p.name = :name where p.id = :id");
For ( int x=0; PersonsList.length; x++ ) {
// add name and id parameters
em.executeUpdate();
}
问题:
- 这就是批量更新所需的全部内容吗?还需要添加其他内容吗?
我设置了
hibernate.jdbc.batch_size", "20"
- 默认情况下是否启用了乐观锁定?(虽然我的实体中没有 @Version)
- 如果没有@Version,我需要做什么才能强制执行乐观锁定?
选项2:
使用Select Case
语法或 Criteria API
构造一个单一查询
问题:
- 这里是否仍然发生批处理?(在一个大查询中)
- 在性能方面,这是否比第一种方法更好?
- 这两种方法中哪种是推荐的方法?有没有更好的方法?
em.begin()
开始批处理,然后调用每个DML,最后使用em.commit();
提交即可。 - user2511414batch_size
值在10到35之间(取决于情况),对于非常重的负载,请使用数据库优先方式 :) - user2511414