Bulk Update/Delete using the Criteria API in JPA 2.1/Java EE 7
Join the DZone community and get the full member experience.Join For Free
It has long been possible to do bulk updates and deletes using JPQL in JPA. Since JPQL is closely modeled after SQL, it has the key advantages that SQL does - namely that it is a very compact and powerful DSL for relational data manipulation. JPQL is also a natural transition mechanism to JPA for folks that have worked with SQL for a while (such as myself).
The big drawback for JPQL is that it is decoupled from the Java compiler and thus less type-safe/more error-prone. This weakness becomes particularly salient while needing to dynamically construct queries at runtime (with JPQL this basically turns into a lot of hard-to-read string manipulation) or with folks coming from a Java/OO background without much preexisting experience with SQL/RDBMS. For these reasons, the type-safe, Java centric Criteria Query API was added to JPA 2.0/Java EE 6.
In JPA 2.1/Java EE 7 the Criteria API has been moved even closer to JPQL with the addition of bulk update and delete capabilities (the Criteria API in JPA 2.0 supported queries which is by far still the primary use case for the API). Hantsy Bai has a very nice post demonstrating how bulk updates/deletes look like using the JPA 2.1 Criteria API.
For a more basic overview of the Criteria API itself, you should check out the official Java EE 7 tutorial.
Published at DZone with permission of Reza Rahman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Microservices With Apache Camel and Quarkus (Part 2)
13 Impressive Ways To Improve the Developer’s Experience by Using AI
Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
What Is Envoy Proxy?