1 Reply Latest reply on Dec 23, 2008 10:40 AM by getaceres

    Recomended approach for using JPA and JDBC together?

      I want to use new JPA Entities in conjunction with straight JDBC (because of an existing stored procedure layer). Is there a recommended approach for acquiring the connection to do the JDBC operations?

      I have tried the following two approaches and both seam to work, In A I retrieve a connection from the same data source that the entity manager is using. In B, I use getDelegate() to obtain the Hibernate session and then borrow / release a connection.

      I am leaning towards A but, I am worried that the two connections are actually different instances. As for B it's more programmatic, centric to JBoss/Hibernate, and am not sure about the whole borrow / release deal. I see that there is also a plain getConnection() on ConnectionManager and I'm really not sure which approach is intended to be used in this situation if any ....

      I am also unclear as to any transactional implications. Although at this point both look to be operating as expected.

      A)

      1. look up an entity via the entity manager
      2. modify the entity
      3. flush the entity manager so the modifications are visible
      4. retrieve the data source via a JNDI lookup
      5. get a connection from the data source
      6. execute JDBC operation to verify the modification is visable

      B)
      1. look up an entity via the entity manager
      2. modify the entity
      3. flush the entity manager so the modifications are visible
      4. get a connection from the entity manager via:

      Object obj = (Object) em.getDelegate();
      org.hibernate.impl.SessionImpl session = (SessionImpl) obj;
      JDBCContext jdbcCtx = session.getJDBCContext();
      ConnectionManager cm = jdbcCtx.getConnectionManager();
      Connection conn = cm.borrowConnection();

      5. execute JDBC operation to verify the modification is visable
      6. release the connection via cm.releaseBorrowedConnection();

        • 1. Re: Recomended approach for using JPA and JDBC together?
          getaceres

          I'm using the first approach since it's more portable. I'm using in in an EJB3 so the transaction is automatically managed and the connection is really referring to the same database. I don't know I will have problems in the future, but right now I'm looking for portability and upgradability.