update existing column value in JPA CriteriaUpdate
Asked Answered
Q

2

10

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();
Quincuncial answered 2/7, 2015 at 13:35 Comment(0)
S
15

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();
Stempson answered 2/7, 2015 at 13:46 Comment(1)
I understand CriteriaUpdate bypasses optimistic locking. If you wanted to use optimistic locking here, how would that be accomplished?Timework
C
-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.

Childhood answered 8/6, 2023 at 3:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.