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.
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.
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.
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.
Using JdbcTemplate and controlling the Connection gives you. Leveraging TransactionTemplate and the abstraction it provides over the above. Annotating functions with @Transactional(propagation = Propagation.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With