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

    Recomended approach for using JPA and JDBC together?

    Dan Bush Newbie

      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();