4 Replies Latest reply on Jul 24, 2008 11:09 AM by sradford

    Code hook just prior to JPA session closing

    sradford

      Hi,


      I have a requirement that requires some code to run (and manipulate entities that might cause a flush) just before the JPA/Hibernate session closes. Anyone any ideas on how to achieve this?


      Thanks,


      Sean

        • 1. Re: Code hook just prior to JPA session closing

          Maybe @PrePersist, @PreUpdate, @PreRemove could do the trick?

          • 2. Re: Code hook just prior to JPA session closing
            sradford

            Nope. @PrePersist, @Pre.... won't do as I can't run a JPA Query and even if manipulating entities via relationships, a flush could occur resulting in possible recursion....

            • 3. Re: Code hook just prior to JPA session closing
              gjeudy

              How about:


              org.hibernate.Interceptor.preFlush()

              ?


              You inject(spring, spring/seam integration) or lookup(JNDI) a SessionFactory to your interceptor instance. If you try injection, inject the SessionFactory in a static field so that the separate Interceptor instance created on the persistence unit creation will have a hold to the same ref.


              You can then open an independent session to perform your query inside your interceptor code.


              You can add the below to activate your interceptor in your persistence.xml. You will have only 1 interceptor instance shared across all sessions to it has to be thread-safe.


              <property name="hibernate.ejb.interceptor" value="a.b.c.YourInterceptor" /> 
                             


              To avoid possible recursive calls to your interceptor pass

              SessionFactory.openSession(org.interceptor.EmptyInterceptor.INSTANCE);

              when used inside the interceptor. EmptyInterceptor will override the default interceptor set in persistence.xml.


              All of this ain't very pretty but I believe it's a workable solution.


              • 4. Re: Code hook just prior to JPA session closing
                sradford

                Hmm. Not too sure. Can't really use a second Session don't think this will fit for me.


                Wondering whether a javax.transaction.Synchronization is the way forward....