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

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

 

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

 
  1.  
  2.  
  3.  


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

 
  1. import javax.annotation.Resource;

  2.  
  3. import org.mybatis.spring.SqlSessionTemplate;

  4. import org.springframework.beans.factory.BeanFactory;

  5. import org.springframework.context.support.ClassPathXmlApplicationContext;

  6. public class Test{

  7. @Resource

  8. public SqlSessionTemplate sqlSession;

  9.  
  10. public static void main(String[] args) {

  11. // TODO Auto-generated method stub

  12. new Test().firstTest();

  13. }

  14.  
  15. public void setSqlSession(SqlSessionTemplate sqlSession) {

  16. this.sqlSession = sqlSession;

  17. }

  18.  
  19. public void firstTest() {

  20. BeanFactory factory = new ClassPathXmlApplicationContext("com/Template/applicationContext.xml");

  21. Test test = (Test)factory.getBean("customerTest");

  22. Customer cus = (Customer)test.sqlSession.selectOne("selectCustomer",10696);

  23. System.out.println(cus);

  24. }

  25. }


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

你可能感兴趣的:(spring)