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

时间:2022-06-28 05:10:47

     今天用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方法的命名就好办了。