11

What happened to the SessionFactoryUtils.getSession method from Hibernate 4 in Spring 3.1.0 ? What should be used instead ? sessionFactory.getCurrentSession() keeps giving me this exception:

org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:883)

Any hint ?

gastaldi
  • 728
  • 1
  • 6
  • 17
  • 1
    I am facing same problem, I am using sessionFactory.getCurrentSession() instead, but I am not sure if it is the right way to go. – craftsman Mar 19 '12 at 06:06

4 Answers4

5

Use sessionFactory.getCurrentSession()

I believe the concept of a "current session" came in Hibernate 3, SessionFactoryUtil was written before this existed.

Darshana
  • 2,462
  • 6
  • 28
  • 54
ianpojman
  • 1,743
  • 1
  • 15
  • 20
1

You have to add a property example:

<prop key="hibernate.current_session_context_class">thread</prop>

to your session factory bean mapping. (check the hibernate documentation for more details)

ElderMael
  • 7,000
  • 5
  • 34
  • 53
1

Not sure why did they remove it, probably they implemented a better design using org.hibernate.context.CurrentSessionContext. As from this post:

... Simply use the plain SessionFactory and use the getCurrentSession method to obtain the current transactional session (don't use openSession!!!!) and you are good to go...

As from documentation of SessionFactory.getCurrentSession():

The definition of what exactly "current" means controlled by the CurrentSessionContext impl configured for use.
craftsman
  • 15,133
  • 17
  • 70
  • 86
  • in marten's post, the key word is "current *transactional* session". So, gastaldi must set up transactional demarcation like I describe in my answer – Hans Westerbeek Apr 08 '12 at 12:45
0

The 'org.hibernate.HibernateException: No Session found for current thread' exception happens when you haven't configured your transaction demarcation properly with Spring.

Typically, Spring opens a session for you when your transaction starts, binds it to a ThreadLocal and re-uses it for the duration of your transaction. When your transaction commits, the session is closed (after it was flushed). So, you don't need to make any calls to the SessionFactory class yourself.

Usually, people put @Transactional on a class (typically a Service) and configure Spring to start and end transactions on method invocations on that class.

Hans Westerbeek
  • 5,645
  • 3
  • 34
  • 35