springboot集成mybatis保姆级教
时间: 2023-12-16 21:04:46 浏览: 99
Springboot开发资源:springboot集成mybatis案例
以下是SpringBoot集成Mybatis的保姆级教程:
1.首先,在pom.xml文件中添加以下依赖:
```xml
<!-- SpringBoot依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- MySQL依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
```
2.在application.properties文件中添加以下配置:
```properties
# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Mybatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
```
3.创建实体类和Mapper接口
```java
// 实体类
public class User {
private Integer id;
private String name;
private Integer age;
// 省略getter和setter方法
}
// Mapper接口
@Mapper
public interface UserMapper {
List<User> findAll();
}
```
4.创建Mapper.xml文件
```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.example.demo.mapper.UserMapper">
<select id="findAll" resultType="com.example.demo.entity.User">
select * from user
</select>
</mapper>
```
5.创建Service和Controller
```java
// Service
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> findAll() {
return userMapper.findAll();
}
}
// Controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> findAll() {
return userService.findAll();
}
}
```
6.启动项目,访问http://localhost:8080/users即可查看结果。
阅读全文