2 Replies Latest reply on Jun 29, 2017 9:45 PM by marcuscf

    Setting context for a JPA connection - is this safe?

    marcuscf

      Hello!

       

      I am using JBoss AS 7.1.x and I need to set some user information (in a database-specific way) before every operation and reset it just before the connection is returned to the connection pool. I intend to use this information to generate better logging in  database triggers, so I will be able to see who did every operation, instead of logging everything as performed by "JBoss" (or other generic name).

       

      We use JPA and some JDBC in @Stateless beans.

       

      What worries me is:

      Could the connection be released between two JPA queries in the same transaction, and used for something else by the container? (the Hibernate documentation says that yes, a connection can be released in this situation, but it is not clear whether it might be used by another transaction or thread) I guess plain JDBC is safe if we set everything at the beginning and reset everything in a finally block (preferably in a @AroundInvoke interceptor, because I want it to be easy to use), but I'm not sure about JPA.

       

      There's much more detail in this Stack Overflow question (too bad I couldn't get a definite answer there):

      http://stackoverflow.com/questions/14045219/setting-context-in-a-jpa-connection-is-this-safe

       

      So, can this approach work reliably? If yes, would it be future-proof and portable? If not, do you have another suggestion as how to pass extra information to database triggers?

       

      Thank you very much.

        • 1. Re: Setting context for a JPA connection - is this safe?
          marcuscf

          So I did some tests with JBoss 7.1.3: I set the connection pool to allow at most 1 connection to the database and created an EJB method that performs a database operation and waits for 30 seconds before returning to the caller.

           

          I found out that in a transactional EJB method (e.g. where TransactionalAttribute is REQUIRED), the connection is not given to other clients during the whole transaction (just as I need). On the other hand, if there is no active transaction, the connection is released as soon as the JPA call ends, before the EJB method returns.

           

          It looks like it is possible to do what I want (as long as I ensure that a transaction is active), but I don't know if this behavior is an implementation detail or if it is expected to be like this per the specification...

          • 2. Re: Setting context for a JPA connection - is this safe?
            marcuscf

            It looks like my answer came a bit too late here: Associate user with database connection from pool

             

            I'm not sure which is the correct answer in that thread but it's better than nothing.