'Hibernate 4 Could not obtain transaction-synchronized Session for current thread

I know it's far not a new question. For example lots of recipies can be found here both in question and replies. However, I didn't manage to solve mine.

I user Hibernate 4 + Spring 4 and PostgreSQL. I have DAO and DAOImpl marked @Transactional for the whole class:

package org.app.server.dao.impl;

@Repository
@Transactional
public class UserDAOImpl implements UserDAO {

  @Autowired
  private SessionFactory sessionFactory;

  public User getUser(String login) {
    User user =
            (User) sessionFactory.getCurrentSession().createQuery("from User p where p.login=:login")
                    .setParameter("login", login).uniqueResult();
    return user;
  }

  @Override
  public void addUser(User user) {
    sessionFactory.getCurrentSession().save(user);
  }
}

User is an @Entity:

package org.app.model;

@Entity
@Table(name = "person")
public class User implements Serializable {
  private static final long serialVersionUID = 1L;

  public User() {
  }

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(columnDefinition = "serial")
  private Integer id;

  @NotNull
  private String login;

  @NotNull
  private String password;

  private String email;

 // getters and setters
}

Now I sign up a User from th form. Controller catches the data:

package org.app.controller;

@Controller
@Scope("prototype")
public class MyController {

@Autowired
private UserOperations userOperations;

  @ModelAttribute("user")
  public User getUserObject() {
    return new User();
  }

  @RequestMapping(value="/newuser", method = RequestMethod.POST)
  public ModelAndView newUser(@ModelAttribute("user") User user, BindingResult result) {
    userOperations.signup(user);
    return new ModelAndView("redirect:/somepage");
  }
}

And sends it to UserOperations @Component in order to check if such login has already existed and insert a new User. Obviously, that must be done in one transaction:

package org.app.server;

@Component
@Scope("prototype")
public class UserOperations {

  @Autowired
  private UserDAO userDAO;

  @Transactional
  public void signup(User user) {
    if (userDAO.getUser(user.getLogin()) == null) {
      userDAO.addUser(user);
    }    
  }
}

So whenn I run it, I have the following:

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
    at org.app.server.dao.impl.UserDAOImpl.getUser(UserDAOImpl.java:30)
    at org.app.server.UserOperations.signup(UserOperations.java:25)
    at org.app.controller.StartPageController.newUser(StartPageController.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Here are my xml configs: applicationContext.xml

<context:component-scan base-package="org.app.server" />
<context:annotation-config />

<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}"
    p:username="${jdbc.username}" p:password="${jdbc.password}" />

<bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
    <property name="dataSource" ref="dataSource"/>
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" depends-on="flyway">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
         <array>
              <value>org.app.server</value>
              <value>org.app.model</value>
         </array>
    </property> 
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.dialect">${jdbc.dialect}</prop>
            <prop key="hibernate.connection.charSet">UTF-8</prop>
            <prop key="hibernate.hbm2ddl.auto">${jdbc.hbm2ddl}</prop>
        </props>
    </property>
</bean>

And springmvc-servlet.xml:

<context:component-scan base-package="org.app.controller, org.app.server" />
<mvc:annotation-driven />
<mvc:default-servlet-handler />

One more interesting thing is that when I use getUser and addUser (signup) separately, directly from Controller, for example, it works fine.



Solution 1:[1]

You must openSession before your call

User user = (User)sessionFactory.getCurrentSession().createQuery("from User p where p.login=:login").setParameter("login", login).uniqueResult();

So you must do :

Session session = sessionFactory.openSession();
User user = (User) session.createQuery("from User p where p.login=:login").setParameter("login", login).uniqueResult();

Solution 2:[2]

Adding @transactional annotation before UserDao.getUser(String login) method should fix this.

Solution 3:[3]

In my case, there was no tx:annotation-driven after the component scan for the specific package.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TOUZENE Mohamed Wassim
Solution 2 mambo
Solution 3