2

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
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
erickdeoliveiraleal
  • 708
  • 2
  • 9
  • 21

1 Answers1

2

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).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197