springboot2整合mybatis
时间: 2023-07-04 13:27:25 浏览: 115
好的,下面是Spring Boot 2整合MyBatis的步骤:
1. 首先,在pom.xml文件中添加以下依赖:
```
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
```
2. 在application.properties文件中配置数据库连接信息:
```
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
```
3. 创建MyBatis的Mapper接口和SQL映射文件:
Mapper接口:
```
public interface UserMapper {
User getUserById(int id);
}
```
SQL映射文件(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.example.demo.mapper.UserMapper">
<select id="getUserById" parameterType="int" resultType="com.example.demo.entity.User">
select * from user where id = #{id}
</select>
</mapper>
```
4. 创建User实体类:
```
public class User {
private int id;
private String name;
private int age;
// 省略getter和setter方法
}
```
5. 在Spring Boot的启动类上添加@MapperScan注解,扫描Mapper接口:
```
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
6. 在Service中使用Mapper:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.getUserById(id);
}
}
```
这样,一个简单的Spring Boot 2整合MyBatis的项目就完成了。
阅读全文