Saturday, July 12, 2008

Deleting References w/ JPA

In my previous post I linked to three excellent videos on JPA. One of them answered a question that had bothered me since I first started using JPA.

One thing that bugged me was trying to delete an object of a particular ID. Since the EntityManager deals with objects, I assumed you had to first find the object before deleting it. For instance, say we have an Order w/ an ID of 17, but all I currently have is the ID value of 17. I thought that you had to do the following to delete the order:

        em.delete(em.find(Order.class, 17));

This bugged me because it seemed like an unnecessary lookup. Why do I need to find the object if I just want to delete the object w/ the associated ID? Well, as covered in the video (slide 35 + 36), JPA has a way around that:

        em.delete(em.getReference(Order.class, 17));

Essentially, JPA creates a "hollow" reference that it then deletes, preventing the unnecessary lookup in the first example. Sure you could accomplish this using a Delete JPQL statement, but as the presenter points out -- using JPQL with a primary key as the parameter usually indicates an anti-pattern to avoid.

0 comments: