ormeclipselinkjpa-2.1

update existing column value in JPA CriteriaUpdate


i have an Entity User, and my DB value for user is:

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

Now i want to run the query

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

How can we achive it through 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();

Solution

  • You can use this code. It will work for you

    // 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();