Ashish Ratan
Ashish Ratan

Reputation: 2870

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

Upvotes: 10

Views: 13760

Answers (2)

Shihan Iqbal
Shihan Iqbal

Reputation: 1

If you are already handling optimistic locking for concurrent updates, you need to increment the version column as part of your update statement manually as the persistence context is not synced with the criteria update/delete.

Upvotes: -1

Amit Kumar
Amit Kumar

Reputation: 166

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

Upvotes: 15

Related Questions