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

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

 

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

<!--创建jdbc数据源 -->
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
                <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
                <property name="url" value="jdbc:oracle:****:*****:1521:****" />  
                <property name="username" value="****" />  
                <property name="password" value="****" />  
      </bean>
	
	  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	  	 <property name="dataSource" ref="dataSource" />
		 <property name="configLocation" value="classpath:com/Template/configuration.xml" />
	  </bean>
	  
	  <bean id="sqlSession"     class="org.mybatis.spring.SqlSessionTemplate"> 
      	  <constructor-arg index="0" ref="sqlSessionFactory" /> 
	  </bean>

	  <bean id="customerTest" class="com.Template.Test">
	  	  <property name="sqlSession" ref="sqlSession" />
	  </bean>



这是测试类,由于这是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方法传值,而抽象类由于是继承的,所以自动赋值。手动赋值的时候需要特别注意的是,<property name="sqlSession" ref="sqlSession" />这里的name就是属性名,写setter方法的时候就是参照它写的,所以setter方法的命名就好办了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值