0

I am trying to load entity by doing this:

public void reloadRepository() {
        Session session = getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Hibernate.initialize(Repository.class);
    }

From this stack overflow post (Hibernate openSession() vs getCurrentSession()), it says

When you call SessionFactory.getCurrentSession, it creates a new Session if it does not exist, otherwise use same session which is in current hibernate context. It automatically flushes and closes session when transaction ends, so you do not need to do it externally.

What does it mean by "transaction ends"? If I don't make any transaction (guessing Hibernate.initialize() is not making transaction), does hibernate close this session?

Jonathan Hagen
  • 580
  • 1
  • 6
  • 29

2 Answers2

1

Probably.

I'm guessing you set current_session_context_class to thread (since you're using beginTransaction). This means that, according to the javadoc, the session is only usable after transaction is started and is destroyed automatically when transaction ends.

I'm not sure what you mean by 'not making any transaction', you just made one using beginTransaction(). Once you commit or rollback, the transaction will end. Even if you do neither, the transaction will eventually time out,and that will also count as ending the transaction.

crizzis
  • 9,978
  • 2
  • 28
  • 47
0

It's written like that because in modern apps you control transactions with the @Transactional annotation. You simply put it on top of the service methods and Hibernate opens a transaction automatically and closes it when it reaches the end of the method.

I don't really know what you think your last row of code is doing but it looks very wrong. If you want to load an entity you can simply write session.get(), add @Transactional to your method and delete session.beginTransaction() and Hibernate.initialize().

InsertKnowledge
  • 1,012
  • 1
  • 11
  • 17