我正在应用程序中使用休眠模式更新列表中的批量条目。
我有一个通过运行特定条件查询从数据库中获取的员工列表。由于整个方法都在事务注释下,因此我想在此列表中添加每位员工。因此,我可以通过仅在雇员对象上调用setter方法来更新列表中的雇员对象,而无需显式调用update方法,因为整个列表对象都在持久上下文中。
到目前为止,我正在使用for循环来迭代列表并通过调用setter方法来更新每个员工 如下所示:
for(Employee emp:empList){
emp.setAge(5);
emp.setAddress("ABC");
}
现在,如果列表中有1000名员工,则像这样进行更新将花费大量时间。在我通过设置相应的setter值而不是通过调用update方法更新持久性上下文中的字段时,如何应用批量操作。
谢谢
答案 0 :(得分:0)
如果使用的是JPA 2.1,请尝试此操作。
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaUpdate<Employee> update = cb.createCriteriaUpdate(Employee.class);
Root<Employee> root = update.from(Employee.class);
//Acces properties by metamodel entity
root.set(Employee_.age, 5);
root.set(Employee_.address, "ABC");
//Add conditions where
update.where([...])
Query query = em.createQuery(update);
query.executeUpdate();
如果您用同一方法执行更多写操作,请小心,因为条件的批量操作不遵守事务的执行顺序。