【问题标题】:update existing column value in JPA CriteriaUpdate更新 JPA CriteriaUpdate 中的现有列值
【发布时间】:2015-09-20 01:47:56
【问题描述】:

我有一个实体用户,我的用户数据库值为:

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

【问题讨论】:

    标签: orm eclipselink jpa-2.1


    【解决方案1】:

    您可以使用此代码。它会为你工作

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

    【讨论】:

    • 我了解CriteriaUpdate 绕过乐观锁定。如果你想在这里使用乐观锁,那将如何实现?
    猜你喜欢
    • 2020-03-13
    • 2022-12-13
    • 1970-01-01
    • 2020-05-09
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多