SpringBoot - MyBatis-Plus - UpdateWrapper、LambdaUpdateWrapper和LambdaUpdateChainWrapper的用法(四)

写在前面

和SpringBoot - MyBatis-Plus - QueryWrapper、LambdaQueryWrapper和LambdaQueryChainWrapper的用法(二)的用法类似,另外UpdateWrapper、LambdaUpdateWrapper和LambdaUpdateChainWrapper还提供了:set、setSql和setEntity的方法。

UpdateWrapper

// 1. 查询条件:商品标题中包含'学生白色丝袜'并且状态为上架的商品
UpdateWrapper<MallxSpu> updateWrapper = new UpdateWrapper<>();
updateWrapper.like("title","学生白色丝袜").eq("statue",1);

// 2. 将满足条件的商品添加标签
MallxSpu spu = new MallxSpu();
spu.setTag("丝袜");

// 3. 执行更新
int result = mallxSpuMapper.update(spu, updateWrapper);

LambdaUpdateWrapper

方式一:
// 1. 查询条件:商品标题中包含'学生白色丝袜'并且状态为上架的商品
LambdaUpdateWrapper<MallxSpu> updateWrapper = new LambdaUpdateWrapper<>();
queryWrapper.like(MallxSpu::getTitle,"学生白色丝袜").eq(MallxSpu::getStatus,1);

// 2. 将满足条件的商品添加标签
MallxSpu spu = new MallxSpu();
spu.setTag("丝袜");

// 3. 执行更新
int result = mallxSpuMapper.update(spu, updateWrapper);
方式二(使用UpdateWrapper的set方法直接设置字段为待修改的值):
// 1. 查询条件:商品标题中包含'学生白色丝袜'并且状态为上架的商品,并将符合条件的商品打上标签。
LambdaUpdateWrapper<MallxSpu> updateWrapper = new LambdaUpdateWrapper<>();
queryWrapper.like(MallxSpu::getTitle,"学生白色丝袜").eq(MallxSpu::getStatus,1).set(MallxSpu::getTag, "丝袜");

// 2. 执行更新
int result = mallxSpuMapper.update(null, updateWrapper);
方式三(使用UpdateWrapper的set方法和对象混合使用,设置字段为待修改的值):
// 1. 查询条件:商品标题中包含'学生白色丝袜'并且状态为上架的商品,并将符合条件的商品打上标签。
LambdaUpdateWrapper<MallxSpu> updateWrapper = new LambdaUpdateWrapper<>();
queryWrapper.like(MallxSpu::getTitle,"学生白色丝袜").eq(MallxSpu::getStatus,1).set(MallxSpu::getTag, "丝袜");

// 2. 将满足条件的商品的库存改为10000
MallxSpu spu = new MallxSpu();
spu.setStock(10000);

// 3. 执行更新
int result = mallxSpuMapper.update(spu, updateWrapper);
方式四(使用UpdateWrapper的setSql方法设置字段为待修改的值):
// 1. 查询条件:商品标题中包含'学生白色丝袜'并且状态为上架的商品,并将符合条件的商品打上标签,同时修改库存。
LambdaUpdateWrapper<MallxSpu> updateWrapper = new LambdaUpdateWrapper<>();
queryWrapper.like(MallxSpu::getTitle,"学生白色丝袜").eq(MallxSpu::getStatus,1).setSql("tag = '丝袜'").setSql("stock = 10000");

// 2. 执行更新
int result = mallxSpuMapper.update(null, updateWrapper);

LambdaUpdateChainWrapper

方式一:
// 查询条件:商品标题中包含'学生白色丝袜'并且状态为上架的商品,并将符合条件的商品打上标签,同时修改库存,并执行更新操作。
boolean flag = new LambdaUpdateChainWrapper<>(mallxSpuMapper)
        .like(MallxSpu::getTitle,"学生白色丝袜")
        .eq(MallxSpu::getStatus,1)
        .setSql("tag = '丝袜'")
        .setSql("stock = 10000")
        .update();
方式二:
// 1. 将满足条件的商品的库存改为10000
MallxSpu spu = new MallxSpu();
spu.setStock(10000);

// 2. 查询条件:商品标题中包含'学生白色丝袜'并且状态为上架的商品,并将符合条件的商品打上标签,同时修改库存,并执行更新操作。
boolean flag = new LambdaUpdateChainWrapper<>(mallxSpuMapper)
        .like(MallxSpu::getTitle,"学生白色丝袜")
        .eq(MallxSpu::getStatus,1)
        .setSql("tag = '丝袜'")
        .update(spu);

你可能感兴趣的:(SpringBoot,spring,boot)