1.简介
Spring Boot是一款快速开发Web应用程序的框架,MyBatis是一款数据库访问框架,MySQL是一款开源关系型数据库。本文将介绍如何在Spring Boot中整合MyBatis并集成MySQL,实现基本的数据增删改查功能。
2.环境搭建
本文的环境为:JDK1.8,Spring Boot2.2.4.RELEASE,Mybatis3.5.6,MySQL8.0.21。
在开发过程中需要集成相关依赖,可以通过Maven或者Gradle等工具进行构建。
3.Spring Boot整合Mybatis
在项目中引入Mybatis,只需在pom.xml中添加如下依赖即可:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
4.配置MySQL数据库
在src/main/resources目录下添加application.properties文件,进行MySQL的相关配置,如下:
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
以上配置中,url为MySQL数据库连接地址,需要根据实际情况进行修改;username和password为MySQL登录账号和密码;driver-class-name为MySQL数据库驱动。
5.实现数据增删改查
(1)创建实体类User
public class User {
private Long id;
private String name;
private String password;
//getter and setter method
}
(2)创建Mapper接口
@Mapper
public interface UserMapper {
@Insert("INSERT INTO user(name, password) VALUES(#{name}, #{password})")
int insert(User user);
@Delete("DELETE FROM user WHERE id=#{id}")
int deleteById(Long id);
@Update("UPDATE user SET name=#{name}, password=#{password} WHERE id=#{id}")
int update(User user);
@Select("SELECT * FROM user WHERE id=#{id}")
User findById(Long id);
@Select("SELECT * FROM user")
List<User> findAll();
}
(3)创建Service服务
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int insert(User user) {
return userMapper.insert(user);
}
public int deleteById(Long id) {
return userMapper.deleteById(id);
}
public int update(User user) {
return userMapper.update(user);
}
public User findById(Long id) {
return userMapper.findById(id);
}
public List<User> findAll() {
return userMapper.findAll();
}
}
(4)创建Controller控制器
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("")
public int insert(User user) {
return userService.insert(user);
}
@DeleteMapping("/{id}")
public int deleteById(@PathVariable Long id) {
return userService.deleteById(id);
}
@PutMapping("")
public int update(User user) {
return userService.update(user);
}
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@GetMapping("")
public List<User> findAll() {
return userService.findAll();
}
}
6.结束语
通过以上实现,我们已经成功整合Spring Boot和Mybatis,并成功集成MySQL数据库,实现了基本的数据增删改查功能。本文只是一个demo,实际开发中还需考虑更多的实际情况,例如异常处理等,希望对大家有所帮助。