Announcement Announcement Module
Collapse
No announcement yet.
How to use Hibernate and JDBC under the same transaction? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to use Hibernate and JDBC under the same transaction?

    I just implemented a DAO layer using Spring and Hibernate, and I'm really impressed how less efforts it took comparing to usual plain-Hibernate code.

    But now I have to integrate a bunch of queries and updates written by DBA into the main application. Those are going to be executed as JDBC code. It's very desirable to run them under the same transaction as hibernate, i.e.:

    tx.begin();
    hibDao.doSmth(foo);
    jdbcDao.doSmth(bar);
    tx.commit();

    Is it possible?

    P.S. I tried to pass a reference to datasource to hibernateTransactionManager, but it throwed exception saying it need a session.

    P.P.S. Note that I'm currently use local transactions, but it cannot be completely excluded that one day the code will move under JTA...

  • #2
    You can wrap your existing DataSource in a TransactionAwareDataSourceProxy and pass that to Hibernate's SessionFactory and your JdbcTemplate. If your transaction manager is the HibernateTransactionManager (or any PlatformTransactionManager, IIRC) then JDBC and Hibernate can share a transaction.

    You should also set the property useTransactionAwareDataSource on LocalSessionFactoryBean to true.

    Regards,
    Patrick.

    Comment


    • #3
      Or just use the same connection that you can get from your Hibernate session -

      Code:
      java.sql.Connection con = session.connection();

      Comment


      • #4
        Just make sure that the LocalSessionFactoryBean and your JdbcTemplate/JdbcDaoSupport reference the same DataSource. Set the LocalSessionFactoryBean as a refernce for the HibernateTransactionManager. All the transaction coordination will then be handled by the HibernateTransactionManager for both Hibernate and JDBC code as long as you also use Spring's JDBC support.

        Comment

        Working...
        X