No Hibernate Session bound to thread configuration does not allow creation of non-transactional one

In my Spring application, I am using a DAO - service pattern to retrieve records from database. I have a DAO class that directly accesses the Hibernate session, and a service class that wraps the DAO calls. However, when I call a service method from my controller class, I get the following error:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687)
com.wordgraphs.dao.UserDao.getByName(UserDao.java:20)


My DAO looks like this:
UserDao.java
@Repository
public class UserDao extends GenericDaoImpl<User>
{
@SuppressWarnings("unchecked")
public List<User> find (String name) throws OrgStatsException
{
Criteria c = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(getType());

c.add(Restrictions.eq("name", name);

return (List<User>)c.list();
}
}


The service method that calls the DAO method is:
UserService.class
@Service
public class UserService
{
@Inject
UserDao userDao;

public List<User> find (String name)
{
return userDao.find(name);
}

}


Then there is a controller method that calls the UserService.find methods.

Does anyone have any idea what the error means?
graham on 20-03-2013 10:12
The reason of this error is the use of the getHibernateTemplate().getSessionFactory().getCurrentSession(), which requires an existing Hibernate session. To make this work, you need to make the service method transactional by adding a @Transactional (org.springframework.transaction.annotation.Transactional) annotation:
UserService.java
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService
{
@Inject
UserDao userDao;

@Transactional
public List<User> find (String name)
{
return userDao.find(name);
}

}
graham on 20-03-2013 10:14

Post an answer

Do you have a solution to this problem, or want to comment on it? Other users will appreciate your help!
Your answer or comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems