org.hibernate.HibernateException No Session found for current thread

1. Problem Description
Spring 3.2.6
Hibernate 4.2.0 org.hibernate.HibernateException No Session found for current thread

2. Analysis:
Quoted from R1: getCurrentSession() only makes sense inside a scope of transaction. You need to declare an appropriate transaction manager, demarcate boundaries of transaction and perform data access inside it.

3. Solution:

3.1 Add configuration in application context.

<aop:aspectj-autoproxy /> 

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
	<property name="sessionFactory" ref="sessionFactory" />
</bean>
	
<tx:annotation-driven transaction-manager="transactionManager"/> 
3.2 Add Spring's @Transactional annotation

        @Autowired
	private SessionFactory sessionFactory;

	/**
	 * @return session object
	 */
	private Session currentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	/**
	 * @param operator
	 */
	@Transactional
	public void saveOperator(Operator operator){
		currentSession().save(operator);
	}


References:
1: http://stackoverflow.com/questions/10459922/org-hibernate-hibernateexception-no-session-found-for-current-thread
2: http://www.iteye.com/problems/94825




你可能感兴趣的:(org.hibernate.HibernateException No Session found for current thread)