springboot整合mybatis的增删改查
时间: 2023-05-17 13:04:25 浏览: 138
可以使用MyBatis-Plus来简化代码,具体步骤如下:
1. 在pom.xml文件中添加MyBatis-Plus的依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
```
2. 在application.yml文件中配置数据源和MyBatis-Plus:
```
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.example.demo.entity
```
3. 创建实体类和Mapper接口:
```
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
```
4. 在Controller中注入UserMapper并使用MyBatis-Plus提供的方法进行增删改查:
```
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userMapper.selectById(id);
}
@PostMapping
public boolean save(@RequestBody User user) {
return userMapper.insert(user) > 0;
}
@PutMapping
public boolean updateById(@RequestBody User user) {
return userMapper.updateById(user) > 0;
}
@DeleteMapping("/{id}")
public boolean removeById(@PathVariable Long id) {
return userMapper.deleteById(id) > 0;
}
}
```
阅读全文