今天用SqlSessionTemplate持久化模板來整合spring和mybatis,其實差別不大,就是spring的配置文件裡改一下,測試類改一下就可以瞭,如下
這是spring控制文件的主要內容,需要註意的就是不要忘瞭把sqlsession註入測試類
[html]
<span style="font-size:14px;"><!–創建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></span>
這是測試類,由於這是SqlSessionTemplate,所以不需要繼承
[java]
<span style="font-size:14px;">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);
}
}</span>
總結:用抽象類和模板的區別就是,測試類中由於SqlSessionTemplate不需要繼承,所以傳值時需要手動寫setter方法傳值,而抽象類由於是繼承的,所以自動賦值。手動賦值的時候需要特別註意的是,<property name="sqlSession" ref="sqlSession" />這裡的name就是屬性名,寫setter方法的時候就是參照它寫的,所以setter方法的命名就好辦瞭。