Spring与mybatis的整合实践之SqlSessionTemplate持久化模板

     今天用SqlSessionTemplate持久化模板来整合spring和mybatis,其实差别不大,就是spring的配置文件里改一下,测试类改一下就可以了,如下

 

这是spring控制文件的主要内容,需要注意的就是不要忘了把sqlsession注入测试类


      
                  
                  
                  
                  
      
	
	  
	  	 
		 
	  
	  
	   
      	   
	  

	  
	  	  
	  


这是测试类,由于这是SqlSessionTemplate,所以不需要继承

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test{
	@Resource
	public SqlSessionTemplate sqlSession;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Test().firstTest();
	}
	
	public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
   }

	public void firstTest() {
		BeanFactory factory = new ClassPathXmlApplicationContext("com/Template/applicationContext.xml");
		Test test = (Test)factory.getBean("customerTest");
		Customer cus = (Customer)test.sqlSession.selectOne("selectCustomer",10696);
		System.out.println(cus);
	}
}


总结:用抽象类和模板的区别就是,测试类中由于SqlSessionTemplate不需要继承,所以传值时需要手动写setter方法传值,而抽象类由于是继承的,所以自动赋值。手动赋值的时候需要特别注意的是,这里的name就是属性名,写setter方法的时候就是参照它写的,所以setter方法的命名就好办了。

你可能感兴趣的:(java,EE)