Dmytro Titov
Dmytro Titov

Reputation: 3201

Spring + Hibernate: Session management within @Transactional methods

There's a lot of questions here on this topic, but still I'm not clear with the procedure of managing session within the transaction.

Let's assume there's some repo:

@Repository
public class SomeRepository {
    @Autowired
    protected SessionFactory sessionFactory;

    @Transactional
    public void doSomething() throws IOException {
        Session session = getSession();
        List<SomeEntity> someEntities = session.createCriteria(SomeEntity.class).list();
        for (int i = index; i < someEntities.size(); i++) {
            /* Some ops with entities */
            if (i % 100 == 0) {
                session.flush();
                session.clear();
            }
        }
        session.close;
    }

    protected Session getSession() {
        return sessionFactory.openSession();
    }
}

Is this code correct? Do I really need to open and close (and flush and clear) session manually each time the operation is running? May I use getCurrentSession() instead and forget about flushing and closing (cuz I guess transaction may take care about the lifecycle for me)?

Upvotes: 5

Views: 11074

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

No, it's not correct. To get the session associated with the current Spring transaction, you must use sessionFactory.getCurrentSession().

And you should never close the session: that's the job of Spring, which will close it when the transaction commits/rollbacks, or even later in the open-session-in-view pattern is used.

Flushing is generally not necessary, except in the situation described in the Hibernate documentation, and which consists in avoiding increasing the size of the first-level cache when you insert a large number of entities in batch. In your case, it doesn't make sense.

Upvotes: 10

Related Questions