Announcement Announcement Module
No announcement yet.
Can you use both Hibernate & jdbc dao in same transactio Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Can you use both Hibernate & jdbc dao in same transactio

    Can I have hibernate save a graft of objects and then perform an insert/update using jdbc in the same transaction?


  • #2
    Straight from the reference docs:
    Additionally, HibernateTransactionManager can export the JDBC Connection used by Hibernate to plain JDBC access code. This allows for high level transaction demarcation with mixed Hibernate/JDBC data access completely without JTA, as long as just accessing one database!
    See org.springframework.orm.hibernate.HibernateTransac tionManager


    • #3
      How do you export the JDBC connection used by hibernate so that it can be used by JDBC access code?


      • #4
        Use org.springframework.jdbc.datasource.DataSourceUtil s.getConnection


        • #5
          I looked at the javadoc for DataSourceUtils. It looks like it contains generic methods for obtaining connections. How would I obtain the connection that Hibernate is currently using with this class?

          As you pointed out, the documentation says you can do it, but it does not go into any detail on how.


          • #6
            Ok, perhaps someone can clarify this for me. I have configured a JNDI datasource using JndiObjectFactoryBean and configured my Hibernate session using LocalSessionFactoryBean (setting its dataSource to the above). My jdbc code also uses this same datasource.

            According to the HibernateTransactionManager javadoc, I think I am all set and don't require any changes.

            So, within the scope of a HibernateTransactionManager managed transaction, both Hibernate and my JDBC template should share the same connection.

            Do I have this right?


            • #7
              Yes, HibernateTransactionManager will automatically expose the Hibernate transaction as JDBC transaction for the underlying DataSource, provided that you either specify a "dataSource" on it or use LocalSessionFactoryBean with a "dataSource".

              To make your JDBC access code participate in such a transaction, either fetch your JDBC connections via DataSourceUtils.getConnection (closing them via closeConnectionIfNecessary) or - preferably - use Spring's JdbcTemplate and/or JDBC operation objects, which will automatically participate in such transactions.

              If your JNDI DataSource is a transactional (JTA-aware) DataSource, you could also use Spring's JtaTransactionManager, which will delegate to the J2EE server's transaction subsytem. In that case, you don't need to worry about DataSourceUtils.getConnection (you can still use it though!), as the server's DataSource will already return transactional connections to your code.