更新JPA CriteriaUpdate中的现有列值

时间:2015-07-02 13:35:27

标签: orm eclipselink jpa-2.1

我有一个实体用户,我的用户DB值是:

name     totalScore
--------------------
ABC        25
XYZ        30

现在我想运行查询

update user set totalScore=totalScore+ (2*totalScore);

我们如何通过JPA 2.1 CriteriaUpdate ???

来实现它
CriteriaBuilder criteriaBuilder = em().getCriteriaBuilder();
       //Updates the salary to 90,000 of all Employee's making more than 100,000.
        CriteriaUpdate update = criteriaBuilder.createCriteriaUpdate(User.class);
        Root user = update.from(User.class);
        Expression<Long> abc=user.get("totalScore");

        update.set("totalScore", ?? ); 
// what expression is here to be used to replace old value with new 
        Query query = em().createQuery(update);
        int rowCount = query.executeUpdate();

1 个答案:

答案 0 :(得分:6)

您可以使用此代码。它适合你

// Gives all Employees a 10% raise.

CriteriaUpdate update = criteriaBuilder.createCriteriaUpdate(Employee.class);

Root employee = update.from(Employee.class);

update.set(employee.get("salary"),criteriaBuilder.sum(employee.get("salary"), criteriaBuilder.quot(employee.get("salary"), 10));

Query query = entityManager.createQuery(update);
int rowCount = query.executeUpdate();