Spring is a great framework for dependency injection and it comes with a lot of support classes and utilities for all kind of things. Hibernate is a persistence service with a lot of useful features, that is relatively easy to use. Configuring both frameworks is not always easy. Configuring them together is sometimes hard and it is easy to make mistakes.
This blog addresses a problem in a configuration that is fairly common: use Spring for transaction management on top of a JTA provider and use Hibernate for persistence. Transaction demarcation is easy and declarative with Spring. The problem is that Hibernate sometimes needs to detect the current transaction and this needs to be configured. This leads to hard to detect bugs in applications that rely on auto flushing.
Auto Flushing
Auto flushing is a Hibernate feature which will synchronize in-memory state with database state when a query is executed. Normally, Hibernate will only synchronize in-memory and database state when the session is flushed. With Spring this can be configured to occur when the transaction is committed. This might lead to unexpected behaviour. Look at the code below
public void transactionInterceptedMethod() { Person p = new Person("Maarten"); personDao.save(p); List persons = personDao.findAll(); }Will the new person be in the list of persons? I think everybody would suspect so. In fact, this relies heavily on how Spring and Hibernate are configured.
- The person object will not immediately be inserted into the database when offered to Hibernate. It will be kept in memory, until the session is flushed. (There are exceptions, but this is the general rule).
- The findAll method will look in the database in the same transaction as the one that is used to insert the person object. Still it will only find the new person if it has been inserted into the database in the same transaction before the query is made.
- Spring will commit the transaction and instruct Hibernate to flush the current session only at the end of the method.
Maarten Winkels
Contact
Let’s discuss how we can support your journey.