user689842
user689842

Reputation:

Why hibernate flushes on select queries (EmptyInterceptor)?

I would like to understand a counter intuitive Hibernate behaviour I am seeing. I always thought that "flush" meant that hibernate had a data structure in-memory that has to be written to the DB. This is not what I am seeing.

I have created the following Interceptor:

public class FeedInterceptor extends EmptyInterceptor
{
    @Override
    public void postFlush(Iterator entities)
    {
          System.out.println("postFlush");          
    }
}

Registered it in my ApplicationContext

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
   <property name="entityInterceptor">
      <bean class="interceptor.FeedInterceptor"/>
   </property>
</bean>

But, strange enough, I see "postFlush" written to the console for every row retrieved from the DB from my DAO:

Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Feed feed");
query.list();

Why is that?

Upvotes: 1

Views: 2700

Answers (1)

Alban
Alban

Reputation: 1943

Let's assume Hibernate wouldn't flush the session, then you could have the following situation:

Person p = new Person();
p.setName("Pomario");
dao.create(p);
Person pomario = dao.findPersonByName("Pomario")
//pomario is null?

When finding a person by name, hibernate issues a select statement to the database. If it doesn't send the previous statements first, then the returned result might not be consistent with changes that have been done previously in the session, here the dababase hasn't received the create statement yet, so it returns an empty result set.

Upvotes: 4

Related Questions