Close

JPA Criteria API - Update Operations

[Updated: Apr 14, 2019, Created: Apr 14, 2019]

In Criteria API, the javax.persistence.criteria.CriteriaUpdate interface defines functionality for performing bulk update operations.

Following method of CriteriaBuilder can be used to obtain CriteriaUpdate instance.

CriteriaUpdate<T> createCriteriaUpdate(Class<T> targetEntity)

Following is the CriteriaUpdate snippet:

public interface CriteriaUpdate<T> extends CommonAbstractCriteria {
   Root<T> from(Class<T> entityClass);
   Root<T> from(EntityType<T> entity);
   Root<T> getRoot();
   //Update the value of the specified attribute.   
   <Y, X extends Y> CriteriaUpdate<T> set( SingularAttribute<? super T, Y> attribute, X value);
   <Y> CriteriaUpdate<T> set( SingularAttribute<? super T, Y> attribute, Expression<? extends Y> value);
   <Y, X extends Y> CriteriaUpdate<T> set(Path<Y> attribute, X value);
   <Y> CriteriaUpdate<T> set(Path<Y> attribute, Expression<? extends Y> value);
   CriteriaUpdate<T> set(String attributeName, Object value);
   CriteriaUpdate<T> where(Expression<Boolean> restriction);
   CriteriaUpdate<T> where(Predicate... restrictions);
}

Quick Example

    .................. 
    CriteriaUpdate<Employee> criteriaUpdate = criteriaBuilder.createCriteriaUpdate(Employee.class);
    Root<Employee> employeeRoot = criteriaUpdate.from(Employee.class);
    criteriaUpdate.set(employeeRoot.get(Employee_.salary),
            criteriaBuilder.sum(employeeRoot.get(Employee_.salary), 500d))
                  .where(criteriaBuilder.equal(employeeRoot.get(Employee_.DEPT), "IT"));
    //the equivalent JPQL
    //UPDATE Employee e SET e.salary = e.salary + 500 WHERE e.dept = 'IT'
    entityManager.getTransaction().begin();
    int i = entityManager.createQuery(criteriaUpdate).executeUpdate();
    System.out.println("Entities updated: " + i);
    entityManager.getTransaction().commit();
    ..................

Complete Example

JPA Entity

@Entity
public class Employee {
  @Id
  @GeneratedValue
  private long id;
  private String name;
  private double salary;
  private String dept;
    .............
}

Using CriteriaUpdate

public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          persistEmployees();
          findAllEmployees();
          updateITEmployeesSalaries();
          findAllEmployees();
          updateAllEmployeesSalaries();
          findAllEmployees();
      } finally {
          entityManagerFactory.close();
      }
  }

  private static void updateITEmployeesSalaries() {
      System.out.println("-- increasing IT employees salaries by 500 --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaUpdate<Employee> criteriaUpdate = criteriaBuilder.createCriteriaUpdate(Employee.class);
      Root<Employee> employeeRoot = criteriaUpdate.from(Employee.class);
      criteriaUpdate.set(employeeRoot.get(Employee_.salary),
              criteriaBuilder.sum(employeeRoot.get(Employee_.salary), 500d))
                    .where(criteriaBuilder.equal(employeeRoot.get(Employee_.DEPT), "IT"));
      //the equivalent JPQL
      //UPDATE Employee e SET e.salary = e.salary + 500 WHERE e.dept = 'IT'
      entityManager.getTransaction().begin();
      int i = entityManager.createQuery(criteriaUpdate).executeUpdate();
      System.out.println("Entities updated: " + i);
      entityManager.getTransaction().commit();
      entityManager.close();
  }

  private static void updateAllEmployeesSalaries() {
      System.out.println("-- increasing all employees salaries by different percentage --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaUpdate<Employee> criteriaUpdate = criteriaBuilder.createCriteriaUpdate(Employee.class);
      Root<Employee> root = criteriaUpdate.from(Employee.class);

      CriteriaBuilder.SimpleCase<String, Double> deptCase =
              criteriaBuilder.selectCase(root.get(Employee_.DEPT));
      Expression<Double> caseExpression =
              deptCase.when("IT", criteriaBuilder.prod(root.get(Employee_.SALARY), 1.20))
                      .when("Admin", criteriaBuilder.prod(root.get(Employee_.SALARY), 1.15))
                      .otherwise(criteriaBuilder
                              .prod(root.get(Employee_.SALARY), 1.12));
      criteriaUpdate.set(root.get(Employee_.salary), caseExpression);
      //the equivalent JPQL
      /*UPDATE Employee e SET e.salary =
               CASE
                WHEN e.dept = 'IT' THEN (e.salary * 1.20)
                WHEN e.dept = 'Admin' THEN (e.salary * 1.15)
                ELSE (e.salary * 1.12)
                END*/

      entityManager.getTransaction().begin();
      int rowsUpdated = entityManager.createQuery(criteriaUpdate).executeUpdate();
      System.out.println("entities Updated: " + rowsUpdated);
      entityManager.getTransaction().commit();
      entityManager.close();
  }

  public static void persistEmployees() {
      Employee employee1 = Employee.create("Diana", 2000, "IT");
      Employee employee2 = Employee.create("Rose", 3500, "Admin");
      Employee employee3 = Employee.create("Denise", 2500, "Admin");
      Employee employee4 = Employee.create("Mike", 4000, "IT");
      Employee employee5 = Employee.create("Linda", 4500, "Sales");
      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(employee1);
      em.persist(employee2);
      em.persist(employee3);
      em.persist(employee4);
      em.persist(employee5);
      em.getTransaction().commit();
      em.close();
  }

  private static void findAllEmployees() {
      EntityManager em = entityManagerFactory.createEntityManager();
      System.out.println("-- All employees --");
      Query query = em.createQuery(
              "SELECT e FROM Employee e");
      List<Employee> resultList = query.getResultList();
      resultList.forEach(System.out::println);
      em.close();
  }
}
-- All employees --
Employee{id=1, name='Diana', salary=2000.0, dept='IT'}
Employee{id=2, name='Rose', salary=3500.0, dept='Admin'}
Employee{id=3, name='Denise', salary=2500.0, dept='Admin'}
Employee{id=4, name='Mike', salary=4000.0, dept='IT'}
Employee{id=5, name='Linda', salary=4500.0, dept='Sales'}
-- increasing IT employees salaries by 500 --
Entities updated: 2
-- All employees --
Employee{id=1, name='Diana', salary=2500.0, dept='IT'}
Employee{id=2, name='Rose', salary=3500.0, dept='Admin'}
Employee{id=3, name='Denise', salary=2500.0, dept='Admin'}
Employee{id=4, name='Mike', salary=4500.0, dept='IT'}
Employee{id=5, name='Linda', salary=4500.0, dept='Sales'}
-- increasing all employees salaries by different percentage --
entities Updated: 5
-- All employees --
Employee{id=1, name='Diana', salary=3000.0, dept='IT'}
Employee{id=2, name='Rose', salary=4024.9999999999995, dept='Admin'}
Employee{id=3, name='Denise', salary=2875.0, dept='Admin'}
Employee{id=4, name='Mike', salary=5400.0, dept='IT'}
Employee{id=5, name='Linda', salary=5040.000000000001, dept='Sales'}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.199: H2 Database Engine.
  • hibernate-core 5.4.2.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • hibernate-jpamodelgen 5.4.2.Final: Annotation Processor to generate JPA 2 static metamodel classes.
  • JDK 1.8
  • Maven 3.5.4

JPA - Update Operation in Criteria API Select All Download
  • criteria-api-update-statement
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also