前面讲到了基于mybatis官方的配置mybatis-config.xml对mybatis作配置,今天我们来学习使用mybatis-spring来基于spring容器环境的XML方式配置mybatis。
理解mybatis-spring
以下是官方说明:
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。 使用这个类库中的类, Spring 将会加载必要的 MyBatis 工厂类和 session 类。 这个类库也提供一个简单的方式来注入 MyBatis 数据映射器和 SqlSession 到业务层的 bean 中。 而且它也会处理事务, 翻译 MyBatis 的异常到 Spring 的 DataAccessException 异常(数据访问异常,译者注)中。最终,它并 不会依赖于 MyBatis,Spring 或 MyBatis-Spring 来构建应用程序代码。
要引入的jar包:
dependencies {
runtime group: 'mysql', name: 'mysql-connector-java', version: '5.1.39'
compile group: 'org.springframework', name: 'spring-context', version: '4.3.9.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.9.RELEASE'
compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.2'
compile group: 'com.baomidou', name: 'mybatis-plus', version: '2.3'
testCompile group: 'junit', name: 'junit', version: '4.12'
}
XML配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 构建数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean id="blogTypeHandler" class="org.wbw.mybatisplus.handler.BlogTypeHandler"></bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeHandlers" ref="blogTypeHandler"/>
</bean>
<!-- 利用MapperFactoryBean来创建一个Mapper实例 -->
<bean id="blogMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.wbw.mybatisplus.mapper.BlogMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
Starting
package org.wbw.mybatisplus;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.wbw.mybatisplus.entity.Blog;
import org.wbw.mybatisplus.mapper.BlogMapper;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
BlogMapper blogMapper = context.getBean(BlogMapper.class);
Blog blog = blogMapper.selectBlog(6);
System.out.println(blog);
}
}
写在最后:其实最主要的是利用Mybatis-Spring来将Mybatis相关组件无缝集成到Spring中,然后管理Mapper,mapper注入到业务bean中,尽而就可以使用mybatis了。关于事务这些类似AOP的东西,spring也帮助我们管理了,可以说代码侵入性很低。