spring boot 安装配置 mybatis步骤
时间: 2023-07-31 17:10:23 浏览: 99
好的,下面是 Spring Boot 集成 MyBatis 的步骤:
1.在 pom.xml 文件中添加依赖:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
```
2.在 application.properties 文件中配置数据库连接等信息:
```properties
# 数据库连接信息
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
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
// 实体类
@Data
public class User {
private Integer id;
private String name;
private Integer age;
}
// Mapper 接口
@Mapper
public interface UserMapper {
List<User> getAllUsers();
}
```
4.创建 Mapper 映射文件:
```xml
<!-- UserMapper.xml -->
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="getAllUsers" resultType="com.example.demo.entity.User">
select * from user
</select>
</mapper>
```
5.在 Service 层中使用 Mapper:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
}
```
6.在 Controller 层中调用 Service:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
```
这样就完成了 Spring Boot 集成 MyBatis 的配置和使用。
阅读全文