CriteriaQuery in JPA2.0 provides a type-safe way to do select, it's great. But I am wondering why it won't provide update/delete operation? To bulk update/delete, you have to fall back to old time writing error-prone SQL or JPQL text. IMO, CriteriaQuery for update/delete should not prove difficult as the where cause handling is the same with select.
Hope this would be implemented in next version of JPA.
public interface CriteriaBuilder. Used to construct criteria queries, compound selections, expressions, predicates, orderings. Note that Predicate is used instead of Expression<Boolean> in this API in order to work around the fact that Java generics are not compatible with varags. Since: Java Persistence 2.0.
For a particular CriteriaQuery object, the root entity of the query, from which all navigation originates, is called the query root. It is similar to the FROM clause in a JPQL query. Create the query root by calling the from method on the CriteriaQuery instance.
The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax.
Because JPA is the ORM tool which the motivation is to map the database records to the objects such that the database records can be manipulated using the programming language instead of SQL , it does not encourage the use of SQL/HQL/JPQL to perform the update.
To prevent from using error-prone SQL or JPQL to update the objects , once you use CriteriaQuery
to retrieve a list of object , you can simply loop through the result objects and then change the properties of the object one by one in order to do the bulk update or delete. JPA should be able to detect the changes made on these objects and generate the suitable SQLs to update the corresponding records in a batch when the EntityManager.flush()
is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With