2

We have a FlushEventListener to do audit functionality. While updating some entity, hibernate will callback our audit code just before flushing. The audit code needs to query the database.

If we try to do it in the same session apparently we mess up the session's state: we get a NullPointerException from inside hibernate, at some point when it's validating naturalIds inside a class named NaturalIdXrefDelegate.

We currently solved it by opening a new session for the audit query. The problem with this is we're losing the benefit of getCurrentSession (a session for the whole request, managed by hibernate). This way we're going back to opening one session per query.

Is there an elegant solution for this or we basically need to re-implement getCurrentSession to manage our own session #2 in the request?

Victor Basso
  • 5,556
  • 5
  • 42
  • 60

1 Answers1

1

You don't have to open new session. It's enough to temporarily disable flush.

Session session = entityManager.unwrap(Session.class);
session.setHibernateFlushMode(FlushMode.MANUAL);
// do your db stuff
session.setHibernateFlushMode(FlushMode.AUTO);

It's actually a lot faster than

session.getSessionFactory().openSession()

Which works to btw.

dagi12
  • 449
  • 1
  • 5
  • 20