Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate and JDBC in one transaction

I have a method, marked as @Transactional. It consists of several functions, one of them uses JDBC and the second one - Hibernate, third - JDBC. The problem is that changes, made by Hibernate function are not visible in the last functions, that works with JDBC.

@Transactional
void update() {
  jdbcUpdate1();
  hibernateupdate1();
  jdbcUpdate2(); // results of hibernateupdate1() are not visible here    
}

All functions are configured to use the same datasource:

<bean id="myDataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
        <property name="targetDataSource" ref="targetDataSource"/>
    </bean>

    <bean id="targetDataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" lazy-init="true" scope="singleton">
       <!-- settings here -->
    </bean>

myDataSource bean is used in the code. myDataSource.getConnection() is used to work with connections in jdbc functions and

getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
               ... 
            }
        });

is used in hibernate function. Thanks.

like image 834
alex543 Avatar asked Nov 11 '10 10:11

alex543


People also ask

Can we use JDBC and Hibernate together?

You can safely mix hibernate with spring JDBC and both should be able to share transactions managed by HibernateTransactionManager . Keep in mind you should be using spring templates to achieve this because they are able to detect and reuse thread-bound connection with active transaction.

Can we use both JPA and JDBC?

JPA-based applications still use JDBC under the hood. Therefore, when we utilize JPA, our code is actually using the JDBC APIs for all database interactions. In other words, JPA serves as a layer of abstraction that hides the low-level JDBC calls from the developer, making database programming considerably easier.

Can Hibernate session have multiple transactions?

Obviously, you can. A hibernate session is more or less a database connection and a cache for database objects. And you can have multiple successive transactions in a single database connection. More, when you use a connection pool, the connection is not closed but is recycled.

Can we use JDBC template with @transactional?

Using JdbcTemplate and controlling the Connection gives you. Leveraging TransactionTemplate and the abstraction it provides over the above. Annotating functions with @Transactional(propagation = Propagation.


1 Answers

First, avoid using JDBC when using hibernate.

Then, if you really need it, use to Session.doWork(..). If your hibernate version does not yet have this method, obtain the Connection from session.connection().

like image 80
Bozho Avatar answered Sep 27 '22 19:09

Bozho