简介
在前面的讨论里已经提到了mybatis的各种配置和操作。从原生的使用角度来看,其实还是有点繁琐的,因为要配置数据源、指定配置文件,设定mapper文件以及接口。在实际的应用中,单纯使用mybatis的机会并不多,它更多的是和spring结合起来用。这里,我们就结合具体的示例讨论详细的配置过程。
和spring的集成
mybatis和spring的集成需要额外加入一些依赖的库,重点是mybatis-spring这个库。详细的依赖库定义如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yunzero</groupId>
<artifactId>mybatisspring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatisspring</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<slf4j.version>1.7.5</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.6.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
这里引用的库比较多,其中spring相关的主要是应用中需要使用到的对于事物以及依赖注入等相关特性。
在配置好基本的依赖之后,下一步就是要配置相关的bean了,这里一般都放在applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.yunzero" />
<context:property-placeholder location="classpath:application.properties" />
<mybatis-spring:scan base-package="com.yunzero.mappers"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.yunzero.domain"/>
<property name="typeHandlersPackage" value="com.yunzero.typehandlers"/>
<property name="mapperLocations" value="classpath*:com/yunzero/**/*.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
这里有不少的配置信息,前面几个是定义了依赖注入支持的方式,对于mybatis来说,重点在于
<mybatis-spring:scan base-package="com.yunzero.mappers"/>
这部分指定了mybatis里mapper接口定义所放的地方。这样以后所有的mapper接口都放到这个指定的包下面就可以。在下面接着定义的sqlSession,sqlSessionFactory这两个bean就相当于配置好了对应数据源和对应在spring里怎么使用sqlSession的模板。
下面的transactionManager主要用来设定业务逻辑层里对事物的支持。
基本上把上面那些东西给配好,差不多就完成了。剩下的就是对应的mapper配置文件了。以StudentMapper为例,它的配置和前面的配置一样:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.yunzero.mappers.StudentMapper"> <resultMap type="Address" id="AddressResult"> <id property="addrId" column="addr_id"/> <result property="street" column="street"/> <result property="city" column="city"/> <result property="state" column="state"/> <result property="zip" column="zip"/> <result property="country" column="country"/> </resultMap> <resultMap type="Student" id="StudentWithAddressResult"> <id property="studId" column="stud_id"/> <result property="name" column="name"/> <result property="email" column="email"/> <association property="address" resultMap="AddressResult"/> </resultMap> </mapper>
mapper文件主要起到一个定义对象和数据库字段映射的作用。剩下的mapper接口部分也很类似,比如AddressMapper:
public interface AddressMapper {
@Select("select addr_id as addrId, street, city, state, zip, country from ADDRESSES where addr_id=#{id}")
Address selectAddressById(int id);
@Insert("insert into ADDRESSES(street, city, state, zip, country) values(#{street},#{city},#{state},#{zip},#{country})")
int insertAddress(Address address);
}
在设置好上述内容之后,还有一个重要的东西就是对定义service层,对mapper的访问进行封装。在之前的示例里,我们都是通过使用sqlSession来封装mapper,这里因为有了前面的定义,这一部分相当于被mybatis-spring封装起来了。它的实现则更加简单:
@Service
@Transactional
public class StudentService {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private StudentMapper studentMapper;
@Autowired
private AddressMapper addressMapper;
public List<Student> findAllStudents() {
return studentMapper.findAllStudents();
}
public Student findStudentById(Integer id) {
logger.debug("findStudentById :"+id);
return studentMapper.findStudentById(id);
}
public Student findStudentWithAddressById(int id) {
return studentMapper.selectStudentWithAddress(id);
}
public Student createStudent(Student student) {
Address address = student.getAddress();
if(address != null){
addressMapper.insertAddress(address);
}
if(student.getName()==null || student.getName().trim().length()==0){
throw new RuntimeException("Student Name should not be null");
}
studentMapper.insertStudent(student);
return student;
}
// some code emitted...
}
在这个示例里,我们只是直接注入StudentMapper和AddressMapper就可以了。在实际的方法实现里,一般只是对于数据的更新或者删除等操作才使用事物。我们可以将类上面添加的Transactional annotation单独添加到对应的方法上。
在完成上述的步骤之后,一个具有完整功能的spring加mybatis工程就配置好了。详细的细节可以参照后面所带的附件。
和spring boot的集成
在这些年来,我们在开发中使用spring boot来越来越多。spring boot对约定强于配置的方式支持使得我们开发的过程中省略了很多繁琐的配置。对于很多工程,它也提供了默认的配置,我们只需要做一点少量的修改。那么,如果基于它来和mybatis集成的话,会是怎么样呢?
我们先看看对应的依赖配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yunzero</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatisspringboot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
这里pom文件的定义反而简单了很多,因为是了spring-boot的模板,它这里有一个spring-boot-starter-parent的父工程,这里就已经将很多东西配置好了。这里配置依赖的mysql-connector等都不需要指定具体的版本号,由spring-boot里的模板事先指定好了,这样可以尽量的避免各种引入的包冲突。
另外,为了保证数据库连接的性能,这里还额外引入了一个数据库连接池的库HikariCP。
在把上述东西配好之后,我们只需要在对应的配置文件里设定几个相关的配置了,在spring-boot里,典型的配置文件就是系统默认生成的application.properties文件。还有一个常用的就是application.yml文件。这里采用yml文件。它的具体配置内容如下:
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/elearning
driver-class-name: com.mysql.jdbc.Driver
username: root
password: password
mybatis:
type-handlers-package: com.yunzero.typehandlers
type-aliases-package: com.yunzero.domain
它的配置样式和properties文件差不多,只是在某些情况下表达方式显得灵活一些。因为这里是针对数据库连接池的配置,所以它的datasource.type下面就需要配置上对应的HikariDataSource。当然,针对Hikaricp,它还有一些具体的参数,也可以配置在这里。
在配置好上述内容之后,剩下的就只要配上对应的mapper文件和mapper接口了。像之前需要配置各种sqlSession, sqlSessionFactory之类的东西都给省了。因为这些spring-boot都已经事先设置好了。其他部分都不需要做任何的修改就可以了。详细的内容也可以参照后续的附件。
总结
总的来说,mybatis和spring,spring boot的集成并不复杂。主要是要注意几个需要配置的地方。

本文详细介绍MyBatis与Spring及Spring Boot集成的过程,包括配置依赖、定义Bean、配置mapper文件等内容。
1098

被折叠的 条评论
为什么被折叠?



