spring整合mybatis
在mybaits的基础上进行整合,之前的代码在mybatis的find那篇。
1.导入spring-mybatis的jar包。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
2.创建spring-dao.xml配置文件,这个是用来整合mybatis的数据库,创建
sqlSessionFactory创建
sqlSession。创建
SqlSessionTemplate
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--创建dataSource:使用spring的数据源替换Mybatis的配置-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
<property name="username" value="system"/>
<property name="password" value="zyx520"/>
</bean>
<!--创建sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis.xml"/>
<property name="mapperLocations" value="classpath:com/dao/MyBookMapper.xml"/>
</bean>
<!--这个是SqlSesion-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入,因为没有set方法-->
<constructor-arg ref="sqlSessionFactory"/>
</bean>
<bean id="mybookMapper" class="com.dao.MyBookMapperimpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
3.创建接口的实现类,通过实现类来访问数据。
public class MyBookMapperimpl implements MyBookMapper{
//在开始我们所有操作,都使用sqlSession来执行,spring介入后使用SqlSessionTemplate;
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<Books> selectBooks() {
MyBookMapper myBookMapper = sqlSessionTemplate.getMapper(MyBookMapper.class);
return myBookMapper.selectBooks();
}
}
4.测试
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-dao.xml");
MyBookMapper myBookMapper = applicationContext.getBean("mybookMapper",MyBookMapper.class);
for (Books books : myBookMapper.selectBooks()) {
System.out.println(books);