Search code examples
jpajpql

Correct approach to using JPA 2


I saw this link at Nabble where someone (James Sutherland) stated to someone that they were "executing a delete all JPQL query. This is basically similar to executing your own SQL, you are responsible for executing the query correctly to maintain your constraints.

This is not the normal way to delete objects in JPA. In JPA you normally read the object, then call remove() on it.".

I was wondering if this is true or not; based on how difficult it's been to remove more than simple tables, I'd start thinking this is correct.

My thoughts thus far are to do it like this:

  1. Perform select statements, however particular they may be (e.g.
    select all students where student courses > 4 and marks >= 60 and
    student registration between 2011 and 2012).
  2. Display/edit/delete objects (so EntityManager merge/persist/remove)
  3. Rinse, lather, and so on

Does this sound reasonable as an approach to how one is suppose to use the JPA or am I off base?


Solution

  • The cascading of remove was discussed here: Google App Engine - DELETE JPQL Query and Cascading. Also for instance doing batch updates won't update version column when optimistic locking is used. Thus batch updates/deletes are a bit crippled in JPA.

    But I wouldn't say This is not the normal way to delete objects in JPA. When I need to delete 2, 20 or 200 objects based on some condition selecting and fetching them first just to call remove() on each is a bad idea most of the time.

    After all batch updates/deletes are there in the specification for a reason.