To be continue…
介绍
MyBatisPlus只做增强不做改变,引入它不会对现有工程产生影响。只需简单配置,即可快速进行单表CRUD操作,从而节省大量时间。
官方文档:MyBatisPlus
快速入门
入门案例
- 引入MyBatisPlus依赖
mybatis-plus-boot-starter
集成了MyBatis和MyBatisPlus的所有功能,因此可以用MyBatisPlus的starter代替MyBatis的starter:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
- 定义Mapper
自定义的Mapper继承MyBatisPlus提供的BaseMapper接口,并指定泛型为对应的实体类:
public interface UserMapper extends BaseMapper<User> {
}
BaseMapper接口中定义了基本的单表增删改查方法
常用注解
MyBatisPlus通过扫描实体类,并基于反射获取实体类信息作为数据库表信息。
实体类与数据库表的映射约定为:
- 类名驼峰转下划线作为表名
- 名为id的字段作为主键
- 变量名驼峰转下划线作为表的字段名
若实体类不符合约定的命名,需要使用注解进行配置,常用的注解有:
- @TableName:用于指定表名
- @TableId:用于指定表中的主键字段信息
- @TableField:用于指定表中的普通字段信息
@TableId主键类型 idType枚举类型:
- AUTO:数据库自增长(最常用)
- INPUT:通过set方法自行输入
- ASSIGN_ID:分配ID+接口IdentifierGenerator的方法nextId来生成id,默认实现类为DefaultIdentifierGenerator雪花算法
默认为ASSIGN_ID
使用@TableField的常见场景:
- 成员变量名与数据库字段名不一致
- 成员变量名以is开头,且是布尔值
- 成员变量名与数据库关键字冲突,例如
@TableField("
order")
需要加上反引号 - 成员变量不是数据库字段,例如
@TableField(exist = false)
常用配置
在application.yaml中根据需要添加配置:
mybatis-plus:
type-aliases-package: com.itheima.mp.domain.po
global-config:
db-config:
id-type: auto
核心功能
条件构造器
QueryWrapper和LambdaQueryWrapper通常用于构建select、delete、update的where条件部分
UpdateWrapper和LambdaUpdateWrapper通常只有在set语句比较特殊才使用
尽量使用LambdaQueryWrapper和LambdaUpdateWrapper,避免硬编码
基于QueryWrapper的查询
@Test
// 查询出名字带o的,存款大于1000元的人的id, username, info, balance
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);
}
@Test
// 更新用户名为jack的用户的余额为2000
void testUpdateByQueryWrapper() {
// 要更新的数据
User user = new User();
user.setBalance(2000);
// 更新的条件
QueryWrapper<User> wrapper = new QueryWrapper<User>()
.eq("username", "Jack");
// 执行更新
userMapper.update(user, wrapper);
}
基于UpdateWrapper的更新
@Test
// 更新id为1, 2, 4的用户的余额扣200
void testUpdateWrapper() {
List<Long> ids = List.of(1L, 2L, 4L);
UpdateWrapper<User> wrapper = new UpdateWrapper<User>()
.setSql("balance = balance - 200")
.in("id", ids);
userMapper.update(null, wrapper);
}
基于LambdaQueryWrapper的查询
@Test
void testLambdaQueryWrapper() {
LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>()
.lambda()
.select(User::getId, User::getUsername, User::getInfo, User::getBalance)
.like(User::getUsername, "o")
.ge(User::getBalance, 1000);
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
自定义SQL
利用MyBatisPlus的Wrapper来构建复杂的where条件,然后自己定义SQL语句中剩余的部分
- 基于Wrapper构建where条件
@Test
// 将id在指定范围的用户(例如1、2、4)的余额扣减指定值
void testCustomSqlUpdate() {
List<Long> ids = List.of(1L, 2L, 4L);
int amount = 200;
QueryWrapper<User> wrapper = new QueryWrapper<User>()
.in("id", ids);
userMapper.updateBalanceByIds(wrapper, amount);
}
- 在mapper方法参数中用Param注解声明wrapper变量名称,必须是ew
void updateBalanceByIds(@Param(Constants.WRAPPER) QueryWrapper<User> wrapper, @Param("amount") int amount);
- 自定义SQL,并使用wrapper条件
可以在方法上使用注解,也可以在xml中写SQL
<update id="updateBalanceByIds">
update tb_user
set balance = balance - #{amount} ${ew.customSqlSegment}
</update>
Service接口
- 自定义Service接口继承IService接口
@Service
public interface IUserService extends IService<User> {
}
- 自定义Service实现类,实现自定义接口并继承ServiceImpl类
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
}
- 开发基础业务接口
@Api(tags = "用户管理接口")
@RequestMapping("/users")
@RestController
@RequiredArgsConstructor
public class UserController {
@Qualifier("IUserService")
private final IUserService userService;
@ApiOperation("新增用户接口")
@PostMapping
public void saveUser(@RequestBody UserFormDTO userDTO) {
// 把DTO拷贝到PO
User user = BeanUtil.copyProperties(userDTO, User.class);
// 新增
userService.save(user);
}
@ApiOperation("删除用户接口")
@DeleteMapping("{id}")
public void deleteUserById(@ApiParam("用户id") @PathVariable("id") Long id) {
userService.removeById(id);
}
@ApiOperation("根据id查询用户接口")
@GetMapping("{id}")
public UserVO queryUserById(@ApiParam("用户id") @PathVariable("id") Long id) {
User user = userService.getById(id);
return BeanUtil.copyProperties(user, UserVO.class);
}
@ApiOperation("根据id批量查询用户接口")
@GetMapping
public List<UserVO> queryUserById(@ApiParam("用户id集合") @RequestParam("id")List<Long> ids) {
List<User> users = userService.listByIds(ids);
return BeanUtil.copyToList(users, UserVO.class);
}
}
- 开发复杂业务接口
controller层
@ApiOperation("扣减用户余额接口")
@PutMapping("/{id}/deduction/{money}")
public void deductMoneyById(@ApiParam("用户id") @PathVariable("id") Long id,
@ApiParam("扣减的金额") @PathVariable("money") Integer money) {
userService.deductMoneyById(id, money);
}
service层
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Override
public void deductMoneyById(Long id, Integer money) {
User user = getById(id);
if (user == null || user.getStatus() == 2) {
throw new RuntimeException("用户状态异常!");
}
if (user.getBalance() < money) {
throw new RuntimeException("用户余额不足!");
}
baseMapper.deductMoneyById(id, money);
}
}
mapper层
@Update("update tb_user set balance = balance - #{money} where id = #{id}")
void deductMoneyById(@Param("id") Long id, @Param("money") Integer money);
启动项目,打开swagger页面调试接口
http://localhost:8080/doc.html