终于解决了:No Session found for current thread

使用Spring+Hibernate,获取数据库Session时,总是抛出异常:No Session found for current thread。

在网卡找了好几天,终于解决

http://blog.csdn.net/greensurfer/article/details/8982876


现将我自己的配置贴出来

Spring配置文件spring.xml内容如下:





	
	
	
	
	
		
		
		
		
	

	
		
	

	
	

		
		 

		
		
		
		
		
			
				th05.hibernate
			
		

		
			
				org.hibernate.dialect.HSQLDialect
				
				
				 hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext  
			
		
	

	
	
		 
	
	
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	
	
	
	
 

//测试代码如下
package th05.hibernate;

import java.util.List;

import kpy.SpringInAction.LogWriter;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CustomerDao1{
	
	private SessionFactory sessionFactory;
	
	@Autowired  
    public void setMySessionFactory(SessionFactory sessionFactory){  
		LogWriter.trace(LogWriter.getMethodName(this.getClass().getName()));
		
		//System.out.println("sssssssssssssssssssss   " + (Object)sessionFactory);
		
		this.sessionFactory = sessionFactory;
    }
	private Session currentSession (){
		return this.sessionFactory.getCurrentSession();
	}

	@Transactional
	public Customers getObjById (String id) {
		LogWriter.trace(LogWriter.getMethodName(this.getClass().getName()));
		

		Customers c = null;
		try{
			
			Session session = this.currentSession();
			// get的第二个参数为表的主键
			c = (Customers)session.get(Customers.class, new String("32363240"));
			c.show();
			
		}catch(Exception e) {
			System.out.println(e);
		}
		return c;
	}
}



你可能感兴趣的:(Java,数据库)