Subash Chaturanga
Subash Chaturanga

Reputation: 834

Is there a way to override javax.persistence.EntityManager.persist() method in openjpa

I want to intercept the JPA calls (without touching entity classes) and hence need $subject? Has anybody tried something similar.

Upvotes: 0

Views: 971

Answers (2)

dcernahoschi
dcernahoschi

Reputation: 15240

You can intercept JPA life-cycle events like "onPersist" by specifying default entity listeners for all entities in the orm.xml file. There is no need to touch the entity. For example:

class SomeListener { 
   @PrePersist
   private void prePersist(Object entity){
      //do some stuff before persisting the entity
   }

   @PostPersist
   private void postPersist(Object entity){
       //do some staff after persisting the entity
   }
}

<entity-mappings>
  <persistence-unit-metadata>
    <persistence-unit-defaults>
       <entity-listeners>
          <entity-listener class="SomeListener">
          <pre-persist method-name="prePersist"/>
          <post-persist method-name="postPersist"/>
        </entity-listener>
       </entity-listeners>
     </persistence-unit-defaults>
  </persistence-unit-metadata>
</entity-mappings

Upvotes: 1

Chris
Chris

Reputation: 21145

Every container out there creates a proxy EM, so you can easily look at how spring or glassfish do it. In the persistence.xml you specify the provider class to use, so just point it to your implementation.

But you could just add in event listeners using an ORM.xml file - JPA allows adding default listeners that apply to all entities, so you do not need to touch any of them. What exactly are you after that JPA doesn't already provide?

Upvotes: 1

Related Questions