7

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.

zx_wing
  • 1,918
  • 3
  • 26
  • 39

1 Answers1

2

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.

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
  • 5
    This sounds like reasonable. But it involves at least two transactions, if the records is huge, for example, deleting one million records, this way is not acceptable. I am just thinking the CriteriaQuery has already worked in SQL way that specifies some conditions then does the work. Why not support delete/update in this style as well. Anyway, currently I have to go with plain SQL for batch deleting/updating if the amount is big. – zx_wing Apr 03 '12 at 00:35
  • 2
    @zx_wing valid point, that is why JPA 2.1 introduced `CriteriaUpdate` – G. Demecki Sep 24 '14 at 07:54