基于BaseMapper<User> (指定泛型为你操作的对象)
引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
自定义mapper继承BaseMapper接口
public interface UserMapper extends BaseMapper<User> {}
简单sql语句
![](https://i-blog.csdnimg.cn/blog_migrate/3534721d3933e8d17b17d59050356234.png)
复杂sql语句(Wrapper)
![](https://i-blog.csdnimg.cn/blog_migrate/c5cd396be1753e23d8af3602d5788fa3.png)
例如:查询出名字中带o的,存款大于等于1000元的人的id、username、info、balance字段
@Test
void testQueryWrapper(){
QueryWrapper<User> wrapper = new QueryWrapper<User>()
.select("id", "username", "info", "balance")
.like("username", "o")
.ge("balance", 1000);
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
基于IService
接口:
public interface IUserService extends IService<User> {
}
实现类:
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
}
IService方法:
![](https://i-blog.csdnimg.cn/blog_migrate/1246dbfc0dee0f16ab54fef6204e619c.png)
简单查询:
新增用户,删除用户,根据id查询用户
@ApiOperation("新增用户接口")
@PostMapping
public void saveUser(@RequestBody UserFormDTO userDTO){
//把DTO拷贝到PO
User user= BeanUtil.copyProperties(userDTO, User.class);
//新增
userService.save(user);
}
@ApiOperation("删除用户接口")
@DeleteMapping("{id}") //路径占位符 @PathVariable
public void deleteUserById(@ApiParam("用户id") @PathVariable Long id) {
userService.removeById(id);
}
@ApiOperation("根据id查询用户接口")
@GetMapping("{id}") //路径占位符 @PathVariable
public UserVO queryUserById(@ApiParam("用户id") @PathVariable Long id) {
User user= userService.getById(id);
return BeanUtil.copyProperties(user, UserVO.class);
}
@ApiOperation("根据id批量查询用户接口")
@GetMapping
public List<UserVO> queryUserByIds(@ApiParam("用户id集合") @RequestParam List<Long> ids) {
//查询用户PO
List<User> users=userService.listByIds(ids);
//把po拷贝到vo
return BeanUtil.copyToList(users, UserVO.class);
}