springboot如何集成MyBatisplus实现增删改查
时间: 2024-06-11 10:04:33 浏览: 96
springboot整合mybatisplus实现增删改查操作
1. 导入MyBatisplus依赖
在pom.xml文件中引入MyBatisplus依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
```
2. 配置数据源
在application.properties文件中配置数据源:
```
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
```
3. 配置MyBatisplus
在Spring Boot启动类上添加注解@EnableTransactionManagement和@MapperScan,@MapperScan注解会自动扫描mapper接口并生成实现类,@EnableTransactionManagement注解开启事务支持:
```
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
4. 创建实体类
创建实体类并添加注解@Table和@Id:
```
@Data
@Table(name = "user")
public class User {
@Id
private Long id;
private String name;
private Integer age;
}
```
5. 创建Mapper接口
创建Mapper接口并继承BaseMapper,BaseMapper提供了常见的增删改查方法:
```
public interface UserMapper extends BaseMapper<User> {
}
```
6. 测试增删改查
在Controller中注入UserMapper,调用增删改查方法:
```
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/user/{id}")
public User getById(@PathVariable Long id) {
return userMapper.selectById(id);
}
@PostMapping("/user")
public boolean save(@RequestBody User user) {
return userMapper.insert(user) > 0;
}
@PutMapping("/user")
public boolean updateById(@RequestBody User user) {
return userMapper.updateById(user) > 0;
}
@DeleteMapping("/user/{id}")
public boolean deleteById(@PathVariable Long id) {
return userMapper.deleteById(id) > 0;
}
}
```
以上就是Spring Boot集成MyBatisplus实现增删改查的步骤。
阅读全文