# Spring Boot 集成Mybatis
Spring Boot并没有提供mybaits的集成,但是mybatis实现了,详细信息参看:
[http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/](http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/)
## 两种集成方式
- 基于xml文件
- 基于注解
## 添加依赖
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
```
## 基于xml的集成
### 配置xml文件路径
```
mybatis.mapper-locations=classpath:com/luyou/mybatis/*.xml
```
### 定义接口
```
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.luyou.domain.User;
// 注意这个@Mapper注解必须要
@Mapper
public interface UserXMLMapper {
List<User> findAll();
long save(User user);
}
```
### 定义xml文件
```
<?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.luyou.dao.UserXMLMapper">
<insert id="save" parameterType="com.luyou.domain.User" useGeneratedKeys="true" keyProperty="id">
insert into user (name,birthday,createtime) values (#{name},#{birthDay},#{registerDate})
</insert>
<select id="findAll" resultType="com.luyou.domain.User">
select id,name,birthday birthDay,createtime registerDay from user
</select>
</mapper>
```
### Service层注入
```
@Autowired
private UserXMLMapper userXMLMapper;
```
### 示例
```
@Override
public List<User> queryAll() {
//List<User> list = userDao.queryAll();
//List<User> list = userRepository.findAll();
List<User> list = userXMLMapper.findAll();
return list;
}
@Override
@Transactional
public long save(User user) {
// 参数校验
Assert.notNull(user,"用户不能为空");
Assert.isTrue(user.getId() == 0, "用户id非法,必须为0");
Assert.hasLength(user.getName(), "用户名称不能为空");
Assert.notNull(user.getBirthDay(),"用户生日不能为空");
Assert.notNull(user.getRegisterDate(),"用户注册时间不能为空");
// 新增
//long pk = userDao.save(user);
// 打印主键
// 造成异常
//double result = 1 / 0;
//User afterUser = userRepository.save(user);
userXMLMapper.save(user);
long pk = user.getId();
return pk;
}
```
## 基于注解的集成
### 定义接口
```
package com.luyou.dao;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import com.luyou.domain.User;
@Mapper
public interface UserAnnotationMapper {
@Insert("insert into user (name,birthday,createtime) values (#{name},#{birthDay},#{registerDate})")
@Options(useGeneratedKeys=true,keyProperty="id")
long save(User user);
@Select("select id,name,birthday birthDay, createtime registerDate from user")
List<User> findAll();
}
```
### Service层注入
```
@Autowired
private UserAnnotationMapper userAnnotationMapper;
```
### 示例与上面一致
## 关于Mybatis注解方式
* 从Mybatis在国内的流行来看,多数是以xml方式集成spring的,刚接触注解方式会不习惯。
* xml可以写出很复杂的sql语句,但若写在注解上,那么看起会很不方便,因此Mybatis开发了一种以java代码的方式来写Sql的方法,叫[SQL语句构建器](http://www.mybatis.org/mybatis-3/zh/statement-builders.html),感兴趣可以研究。
* Mybatis官网是为数不多提供中文文档的
