Search code examples
hibernatejdbcfirebirdjaybird

Passing user from user session in Java to Firebird Trigger using Hibernate or JDBC


I have a trigger that is used to audit data modifications. I need to send a query before every JDBC call so it sends user id to Firebird. How could I use it with Hibernate?

JDBC query example:

select rdb$set_context('USER_SESSION','CURRENT_USER', ?) from rdb$database

Solution

  • I know of two ways to achieve this:

    1. Execute a native query to set the value:

      EntityManager em = emf.createEntityManager();
      Query contextSetQuery = em.createNativeQuery(
              "select rdb$set_context('USER_SESSION','CURRENT_USER', ?) from rdb$database");
      contextSetQuery.setParameter(1, "MARK_NATIVE");
      contextSetQuery.getSingleResult();
      
      // other stuff
      

      Getting the result is imperative, as fetching the result is what will actually set the context variable.

    2. Unwrap to a Hibernate Session and set the client info property on the connection

      EntityManager em = emf.createEntityManager();
      Session session = em.unwrap(Session.class);
      session.doWork(connection -> connection.setClientInfo("CURRENT_USER", "MARK_CLIENT_INFO"));
      
      // other stuff
      

      The Jaybird implementation of Connection.setClientInfo will do the same as the native query (and the query in your question).