Update existing column value in JPA CriteriaUpdate

I have an Entity User, and my DB value for the user:

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

Now I want to run a query

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

How can we achieve this through JPA 2.1 CriteriaUpdate ???

CriteriaBuilder criteriaBuilder = em().getCriteriaBuilder();
       //Updates the salary to 90,000 of all Employee 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();
+4
source share
1 answer

You can use this code. He 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();
+5
source

All Articles