SpringBoot整合MyBatis Plus实现增删改查教程
时间: 2023-06-19 12:04:56 浏览: 216
好的,下面是SpringBoot整合MyBatis Plus实现增删改查的教程:
1. 引入依赖
在pom.xml文件中引入MyBatis Plus和MySQL依赖:
```xml
<dependencies>
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
```
2. 配置数据源和MyBatis Plus
在application.properties或application.yml中配置数据源和MyBatis Plus:
```yaml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
global-config:
db-config:
id-type: auto
logic-delete-value: 0
logic-not-delete-value: 1
```
3. 创建实体类和Mapper
创建一个实体类和一个Mapper接口:
```java
// 实体类
@Data
public class User {
private Long id;
private String name;
private Integer age;
}
// Mapper接口
public interface UserMapper extends BaseMapper<User> {
}
```
4. 实现增删改查
在业务逻辑层中实现增删改查:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getById(Long id) {
return userMapper.selectById(id);
}
public List<User> getAll() {
return userMapper.selectList(null);
}
public int save(User user) {
return userMapper.insert(user);
}
public int update(User user) {
return userMapper.updateById(user);
}
public int deleteById(Long id) {
return userMapper.deleteById(id);
}
}
```
5. 测试
在测试类中调用增删改查方法进行测试:
```java
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Test
void getById() {
User user = userService.getById(1L);
System.out.println(user);
}
@Test
void getAll() {
List<User> userList = userService.getAll();
System.out.println(userList);
}
@Test
void save() {
User user = new User();
user.setName("Tom");
user.setAge(18);
userService.save(user);
}
@Test
void update() {
User user = new User();
user.setId(1L);
user.setName("Jerry");
user.setAge(20);
userService.update(user);
}
@Test
void deleteById() {
userService.deleteById(1L);
}
}
```
以上就是SpringBoot整合MyBatis Plus实现增删改查的教程,希望对你有帮助!
阅读全文