You can use all listening before / after loading, pasting, updating or deleting in JPA in two ways:
Using annotation. A simple example of using a Listener is where the object has a transition variable that must be filled after the object has been saved, updated, or loaded, for example:
public class AvailableCreditListener { @PostLoad @PostPersist @PostUpdate public void calculateAvailableCredit(Account account) { account.setAvailableCredit( account.getBalance().add( account.getOverdraftLimit())); } }
An entity class will be annotated using @EntityListeners:
@EntityListeners({AvailableCreditListener.class}) public class Account extends BaseEntity { private BigDecimal balance; private BigDecimal overdraftLimit; @Transient private BigDecimal availableCredit;
Using the persistence.xml configuration file.
Finally, instead of annotations, the XMl mapping file can be used and deployed with the application to specify default listeners. (This mapping file refers to the persistence.xml file.) But an entity can use the @ExcludeDefaultListeners annotation if it does not want to use default listeners.
@ExcludeDefaultListeners @Entity public class Account extends BaseEntity { .... }
In your persistence.xml:
<persistence-unit-metadata> <persistence-unit-defaults> <entity-listeners> <entity-listener class="samples.AvailableCreditListener"/> </entity-listeners> </persistence-unit-defaults> </persistence-unit-metadata>
source share