Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't JPA CriteriaQuery provide update query?

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.

like image 501
zx_wing Avatar asked Apr 02 '12 00:04

zx_wing


People also ask

What is CriteriaBuilder in Java?

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.

What is root in criteria query?

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.

What is Criteria query in JPA?

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.


1 Answers

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.

like image 92
Ken Chan Avatar answered Oct 15 '22 05:10

Ken Chan