Method Invocation On All Entities

#1

Deleting or changing a field of all the entities of some type is fairly easy, using the DELETE and UPDATE clauses, but I would like to know - is there an elegant and efficient way of invocing some method on all persisted entities of some type?

For instance, suppose every entity object should do some operations before it gets deleted, and at some point we want to delete all those entities. It could be usefull if we could invoke some "doBeforeDie" method before the deletion.

One way to achive this could be retrieving one object at a time and invoke the method (using "retrieval by navigation and access"), but I suspect it's not an efficient solution.

Any alternatives?

#2

> is there an elegant and efficient way of invocing some method on all persisted entities of some type?

You have to retrieve the entity objects and then run the method on each object.

> For instance, suppose every entity object should do some operations before it gets deleted, and at some point we want to delete all those entities. It could be usefull if we could invoke some "doBeforeDie" method before the deletion.

You may define a callback or listener for JPA lifecycle events (see this manual page).

ObjectDB Support
#3

Thanks for the quick reply.

I've annotated a method with the PreRemove annotation and for testing purposes, this method only prints a message.

This method gets called when I delete a specific entity object using the remove method, however it doesn't get called when I run a query that deletes all the entities of that type (although those entities do get erased).

This is the deletion part:

em = emf.createEntityManager();

EntityTransaction trans = em.getTransaction();

trans.begin();

em.createQuery("DELETE FROM MyEntity").executeUpdate();

trans.commit();

Did I miss something?

#4

That is correct. Lifecycle events are implemented in JPA as client side events. DELETE and UPDATE queries bypass the JPA client side for direct execution in the database and therefore do not trigger lifecycle events.

ObjectDB Support
#5

I see. I'll retrieve the entity objects and then run the method on each object, as you suggested.

Thank you.

Reply