本文主要讲解如何在Spring Boot下整合MyBatis并访问数据库。MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。(如不了解点击前往)
环境依赖
修改 POM 文件,添加mybatis-spring-boot-starter依赖。值得注意的是,可以不添加spring-boot-starter-jdbc。因为,mybatis-spring-boot-starter依赖中存在spring-boot-starter-jdbc。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
添加mysql依赖。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
数据源
使用 Spring Boot 默认配置
在 src/main/resources/application.yml中配置数据源信息。
spring:
datasource:
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=UTF-8
username: root
password: root
手动创建
在 src/main/resources/config/dataSource.properties 中配置数据源信息。
# mysql
source.driverClassName=com.mysql.jdbc.Driver
source.url=jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=UTF-8
source.username=root
source.password=root
通过 BeanConfig 创建 dataSource 和jdbcTemplate 。
@Configuration
@EnableTransactionManagement
@PropertySource(value = {"classpath:config/dataSource.properties"})
public class BeanConfig {
@Autowired
private Environment env;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(env.getProperty("source.driverClassName").trim());
dataSource.setUrl(env.getProperty("source.url").trim());
dataSource.setUsername(env.getProperty("source.username").trim());
dataSource.setPassword(env.getProperty("source.password").trim());
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate() {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
return jdbcTemplate;
}
}
脚本初始化
先初始化需要用到的SQL脚本。
-- 导出 springboot_test 的数据库结构
CREATE DATABASE IF NOT EXISTS `springboot_test`
USE `springboot_test`;
-- 导出 表 springboot_test.user 结构
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
`name` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`age` int(3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- 正在导出表 springboot_test.user 的数据:~0 rows (大约)
INSERT INTO `user` (`id`, `name`, `age`) VALUES
(1, 'chenjay', 22),
(2, 'lucy', 19),
(3, 'mary', 35);
MyBatis整合
通过注解的方式
实体对象
public class User {
private int id;
private String name;
private int age;
// SET和GET方法
}
DAO相关
@Mapper
public interface UserDao {
@Insert("insert into user(id, name, age) values(#{id}, #{name}, #{age})")
int add(@Param("id") int id, @Param("name") String name, @Param("age") int age);
@Update("update user set name = #{name}, age = #{age} where id = #{id}")
int update(@Param("name") String name, @Param("age") int age, @Param("id") int id);
@Delete("delete from user where id = #{id}")
int delete(int id);
@Select("select id, name, age from user where id = #{id}")
User findUser(@Param("id") int id);
@Select("select id, name, age from user")
List<User> findUserList();
}
Service相关
@Service
@Service
public class UserService {
@Autowired
private UserDao userDao;
public int add(int id,String name,int age) {
return userDao.add(id, name, age);
}
public int update(String name,int age, int id) {
return userDao.update(name, age, id);
}
public int delete(int id) {
return userDao.delete(id);
}
public User findUser(int id) {
return userDao.findUser(id);
}
public List<User> findUserList() {
return userDao.findUserList();
}
}
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/list")
public List<User> findUserList() {
return userService.findUserList();
}
@GetMapping(value = "/{id}")
public User findUser(@PathVariable("id") int id) {
return userService.findUser(id);
}
@PutMapping(value = "/{id}")
public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
@RequestParam(value = "age", required = true) int age) {
if (0 < userService.update(name, age, id)) {
return "success";
} else {
return "fail";
}
}
@DeleteMapping(value = "/{id}")
public String delete(@PathVariable(value = "id") int id) {
if (0 < userService.delete(id)) {
return "success";
} else {
return "fail";
}
}
@PostMapping(value = "/add")
public String postAccount(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name,
@RequestParam(value = "age") int age) {
if (0 < userService.add(id, name, age)) {
return "success";
} else {
return "fail";
}
}
}
通过Postman测试:
- 查询用户
- 查询列表
- 添加用户
- 修改用户
- 删除用户
- 最后再查看用户列表
可以从上图看出删除用户,修改用户,添加用户都对数据库做出了修改。
通过配置文件的方式
Mapper文件配置
在 src/main/resources/mapper/UserMapper.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.chenjie.springboot.learn.dao.UserDao2">
<insert id="add" parameterType="user">
insert into user(id, name, age)
values(#{id}, #{name}, #{age})
</insert>
<update id="update" parameterType="user">
update user
<set>
<if test="name != null ">
name = #{name},
</if>
<if test="age != null ">
age = #{age},
</if>
</set>
where
id = #{id}
</update>
<delete id="delete">
delete from user where id = #{id}
</delete>
<select id="findUserList" resultType="user">
select * from user
</select>
<select id="findUser" resultType="user">
select * from user where id = #{id}
</select>
</mapper>
在 src/main/resources/application.yml中配置数据源信息。
mybatis:
mapper-locations: classpath*:mapper/*.xml
type-aliases-package: com.chenjie.springboot.learn.entity
- mybatis.mapper-locations来指明mapper的xml文件存放位置,我是放在resources/mapper文件下的。
- mybatis.type-aliases-package来指明和数据库映射的实体的所在包。
DAO相关
@Mapper
public interface UserDao2 {
int add(User user);
int update(User user);
int delete(int id);
User findUser(@Param("id") int id);
List<User> findUserList();
}
Service相关
@Service
public class UserService2 {
@Autowired
private UserDao2 userDao;
public int add(int id,String name,int age) {
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
return userDao.add(user);
}
public int update(String name,int age, int id) {
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
return userDao.update(user);
}
public int delete(int id) {
return userDao.delete(id);
}
public User findUser(int id) {
return userDao.findUser(id);
}
public List<User> findUserList() {
return userDao.findUserList();
}
}
Controller相关
@RestController
@RequestMapping("/user2")
public class UserController2 {
@Autowired
private UserService2 userService;
@GetMapping(value = "/list")
public List<User> findUserList() {
return userService.findUserList();
}
@GetMapping(value = "/{id}")
public User findUser(@PathVariable("id") int id) {
return userService.findUser(id);
}
@PutMapping(value = "/{id}")
public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
@RequestParam(value = "age", required = true) int age) {
if (0 < userService.update(name, age, id)) {
return "success";
} else {
return "fail";
}
}
@DeleteMapping(value = "/{id}")
public String delete(@PathVariable(value = "id") int id) {
if (0 < userService.delete(id)) {
return "success";
} else {
return "fail";
}
}
@PostMapping(value = "/add")
public String postAccount(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name,
@RequestParam(value = "age") int age) {
if (0 < userService.add(id, name, age)) {
return "success";
} else {
return "fail";
}
}
}
通过Postman测试:
查询列表
这里就不做其他测试,此测试旨在测试MyBatis可以使用简单的XML来配置和映射原生信息
总结
上面这个简单的案例,让我们看到了 Spring Boot 整合 MyBatis 框架的大概流程。那么,复杂的场景,大家可以参考使用一些比较成熟的插件,例如com.github.pagehelper、mybatis-generator-maven-plugin等。