mybatisplus实现增删改查
MyBatis Plus 是 MyBatis 的增强工具,可以简化 MyBatis 的使用,提供了很多常用的功能,包括增删改查操作。
以下是使用 MyBatis Plus 实现增删改查的示例:
- 引入 MyBatis Plus 依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本</version>
</dependency>
- 创建实体类(Entity)和对应的 Mapper 接口:
// 实体类
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
// Mapper 接口
public interface UserMapper extends BaseMapper<User> {
}
- 配置 MyBatis Plus:
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
- 在业务类中使用 MyBatis Plus 进行增删改查操作:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public void addUser(User user) {
userMapper.insert(user);
}
public void deleteUser(Long id) {
userMapper.deleteById(id);
}
public void updateUser(User user) {
userMapper.updateById(user);
}
public User getUserById(Long id) {
return userMapper.selectById(id);
}
public List<User> getAllUsers() {
return userMapper.selectList(null);
}
}
以上就是使用 MyBatis Plus 实现增删改查的基本步骤。通过引入 MyBatis Plus 依赖,创建实体类和对应的 Mapper 接口,配置 MyBatis Plus,然后在业务类中使用 Mapper 接口进行数据库操作即可
原文地址: https://www.cveoy.top/t/topic/iL4o 著作权归作者所有。请勿转载和采集!