一、前言
昨天在弄 Spring Boot 与 MyBatis 的整合,首先在网上查看了很多人写的文章,参照前人的经验就开始整了,结果整了一天都是 bug,后来自己到官网上查看官方文档后才得以顺手解决,这也让自己以后要吸取教训,最好先看官方文档,然后再实践。结合自己查看的网上关于 Spring Boot 与 MyBatis 整合的文章,有得写的相当复杂,有的是按照文中描述进行实践后发现不行,所以自己再对其进行总结。我使用的是采用 全注解的方式来实现 MyBatis,这也正好符合 Spring Boot 的思想:使用注解,少用配置文件。最后也加上了个使用 XML 配置的代码。
二、整合步骤
1. 在 pom.xml 的文件中添加以下依赖:
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.2.0
mysql
mysql-connector-java
5.1.41
2. 在 application.properties 文件中添加数据库的配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3. 新建 DAO 接口,里面编写增、删、改、查方法
@Mapper
public interface PersonMapper {
/**
* 添加操作,返回新增元素的 ID
*
* @param personDO
*/
@Insert("insert into person(name,age) values(#{name},#{age})")
@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
void insert(PersonDO personDO);
/**
* 更新操作
*
* @param personDO
* @return 受影响的行数
*/
@Update("update person set name=#{name},age=#{age} where id=#{id}")
Long update(PersonDO personDO);
/**
* 删除操作
*
* @param id
* @return 受影响的行数
*/
@Delete("delete from person where id=#{id}")
Long delete(@Param("id") Long id);
/**
* 查询所有
*
* @return
*/
@Select("select id,name,age from person")
List selectAll();
/**
* 根据主键查询单个
*
* @param id
* @return
*/
@Select("select id,name,age from person where id=#{id}")
PersonDO selectById(@Param("id") Long id);
}
这里全部使用的是注解的方式,关于 MyBatis 的所有注解,可以参考 MyBatis 的中文文档。
4. 编写 Controller
@EnableTransactionManagement // 需要事务的时候加上
@RestController
public class PersonController {
@Autowired
private PersonMapper personMapper;
@RequestMapping("/save")
public Integer save() {
PersonDO personDO = new PersonDO();
personDO.setName("张三");
personDO.setAge(18);
personMapper.insert(personDO);
return personDO.getId();
}
@RequestMapping("/update")
public Long update() {
PersonDO personDO = new PersonDO();
personDO.setId(2);
personDO.setName("旺旺");
personDO.setAge(12);
return personMapper.update(personDO);
}
@RequestMapping("/delete")
public Long delete() {
return personMapper.delete(11L);
}
@RequestMapping("/selectById")
public PersonDO selectById() {
return personMapper.selectById(2L);
}
@RequestMapping("/selectAll")
public List selectAll() {
return personMapper.selectAll();
}
@RequestMapping("/transaction")
@Transactional // 需要事务的时候加上
public Boolean transaction() {
delete();
int i = 3 / 0;
save();
return true;
}
}
三、使用 XML 配置