Search code examples
hibernatespringgrailsaop

How to intercept all Hibernate sessions when they're created (Spring / Grails environment)


Is there a way of intercepting all new Hibernate sessions when they're created? I need to access each Session instance to enable a Hibernate filter with a parameter.

The only solution I've gotten working has involved wrapping the SessionFactory, but this involved a lot of semi nasty hacks as well as it required me to implement around 60 methods, where only a few are interesting.

Hibernate's SessionFactory implementation is for some annoying reason declared final so extending it is not an option. I've also tried aspects and Java proxies without any luck.


Solution

  • I've solved this problem (at least until Hibernate provides a proper API for things like this). Short version of the solution:

    1. Proxy the session factory
    2. Intercept method invocations to getCurrentSession and use a CurrentSessionContext implementation we've initialized (not Hibernate).

    Longer version: http://www.developer-b.com/blog/entry/1635/2010/oct/07/intercepting-hibernate-sessions

    Sources / Github: http://github.com/multi-tenant/grails-hibernate-hijacker (still very experimental)

    Thanks for the input!