Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger actions in my JPA mapped classes whenever they are saved to the database?

Tags:

jpa

I want to have a function in one of my JPA annotated classes that is called every time the EntityManager saves them to the database (aka event listener). Is that possible? Preferably, I'd like to distinguish whether it is just about to be saved or has just been saved.

To accomplish what I want, this time I could probably work around with a setter method, but it wouldn't be quite the same.

like image 498
Hanno Fietz Avatar asked Jul 27 '09 14:07

Hanno Fietz


2 Answers

Sure, check out these examples. You have:

  • @PrePersist;
  • @PreUpdate;
  • @PreRemove.
  • @PostPersist;
  • @PostUpdate; and
  • @PostRemove.

(added by Hanno) - Using this answer for starters, I also found this other nice example tutorial.

like image 113
cletus Avatar answered Oct 26 '22 14:10

cletus


This may be irrelevant now, since this thread is a few years old, but I think the tutorial Hanno is referring to is on this other (working) link:

http://www.cereslogic.com/pages/2008/03/31/pizza-shop-iii-jpa-event-listeners/

And there is also another helpful tutorial on this subject here:

http://www.andygibson.net/blog/article/auditing-entities-with-jpa-events/

I thought I contribute with something to the people who may find this thread in the future.

Saludos desde Bolivia

like image 28
Marcelo Salamanca Cox Avatar answered Oct 26 '22 15:10

Marcelo Salamanca Cox