spring怎么整合mybatis-plus
时间: 2023-10-20 09:16:57 浏览: 141
springboot整合mybatis-plus项目源码示例
Spring整合MyBatis-Plus的步骤如下:
1. 引入依赖:在pom.xml文件中添加以下依赖
```xml
<dependencies>
<!--Spring Boot MyBatis Plus Starter-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!--MyBatis Plus 代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!--MyBatis Plus 分页插件-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!--MyBatis Plus 自动填充插件-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!--MyBatis Plus SQL注入器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
</dependencies>
```
2. 配置数据源:在application.yml文件中添加数据源信息
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
```
3. 配置MyBatis-Plus:在application.yml文件中添加MyBatis-Plus配置信息
```yaml
mybatis-plus:
# 实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.example.demo.entity
# 显示SQL语句
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 分页插件配置
page:
helper-dialect: mysql
# 开启分页
reasonable: true
# 每页最多显示条数,默认500条
max-limit: 10000
# 自动填充配置
global-config:
db-config:
# 自动填充创建时间
meta-object-handler: com.baomidou.mybatisplus.extension.handlers.MybatisDefaultMetaObjectHandler
```
4. 创建实体类:创建Java Bean实体类,使用MyBatis-Plus注解定义表名和字段名
```java
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
private Date createTime;
private Date updateTime;
}
```
5. 创建Mapper接口:创建Mapper接口,并继承MyBatis-Plus的BaseMapper接口
```java
public interface UserMapper extends BaseMapper<User> {
}
```
6. 测试:编写测试类,测试MyBatis-Plus的CRUD操作
```java
@SpringBootTest
class MybatisPlusDemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
}
@Test
void testInsert() {
User user = new User();
user.setName("Tom");
user.setAge(20);
user.setEmail("tom@163.com");
int result = userMapper.insert(user);
System.out.println("插入结果:" + result);
}
@Test
void testSelect() {
List<User> userList = userMapper.selectList(null);
System.out.println("查询结果:" + userList);
}
@Test
void testUpdate() {
User user = new User();
user.setId(1L);
user.setName("Jack");
int result = userMapper.updateById(user);
System.out.println("更新结果:" + result);
}
@Test
void testDelete() {
int result = userMapper.deleteById(1L);
System.out.println("删除结果:" + result);
}
}
```
阅读全文