Mybatis-ps的相关用法

一、Wrappers.<实体>lambdaQuery的使用

MP 配置

依赖

<!--springboot整合mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

yml

# mybatis-plus的配置
mybatis-plus:
  type-aliases-package: com.example.demo.entity # 配置包别名
  mapper-locations: classpath:mappers/*.xml # 映射文件的位置
  configuration:
    map-underscore-to-camel-case: true # true自动开启驼峰规则映射
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # mybatis-plus 日志

Service CURD接口

//service接口继承
public interface EmployeeService extends IService<Employee> {
}

//ServiceImpl实现类继承
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
}
//mapper继承
public interface EmployeeMapper extends BaseMapper<Employee> {

    List<Employee> selectAllByLastName(@Param("lastName") String lastName);
}

理论上,我们只需要实现类继承就可以了,但是为了能够更方便地对业务进行扩展,一些复杂场景下的数据处理,MyBatisPlus 提供的 Service 方法可能无法处理,

此时我们就需要自己编写代码,这时候只需我们自己的service中定义自己的方法,并在 ServiceImpl 中实现即可。

 

条件构造器

LambdaUpdateWrapper

UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    updateWrapper.lambda().set(User::getAge, 20)
        .eq(User::getAge, 18);

把年龄为20的全部替换为18。

queryWrapper

QueryWrapper<BannerItem> wrapper = new QueryWrapper<>();
wrapper.eq("banner_id", id);

List<BannerItem> bannerItems = bannerItemMapper.selectList(wrapper);

查询banner_id=id的所有数据

banner_id为数据库的字段,id为前端传过来的参数数据

lambdaQueryWrapper

LambdaQueryWrapper<BannerItem> wrapper = new QueryWrapper<BannerItem>().lambda();
wrapper.eq(BannerItem::getBannerId, id);
List<BannerItem> bannerItems = bannerItemMapper.selectList(wrapper);

Wrappers.<实体>lambdaQuery()---用得比较多,单表查询

复制代码
 1 @Override
 2     public IPage<CommcauseElementVO> listPage(@NonNull CommcauseElementListPageDTO commcauseElementListPageDTO, @NonNull Integer current, @NonNull Integer size) {
 3 
 4         LambdaQueryWrapper<CommcauseElement> wrappers = Wrappers.<CommcauseElement>lambdaQuery()
 5                 .eq(StringUtils.isNotBlank(commcauseElementListPageDTO.getElementCode()),
 6                         CommcauseElement::getElementCode,
 7                         commcauseElementListPageDTO.getElementCode())
 8 
 9                 .eq(StringUtils.isNotBlank(commcauseElementListPageDTO.getElementName()),
10                         CommcauseElement::getElementName,
11                         commcauseElementListPageDTO.getElementName());
12 
13         IPage<CommcauseElementVO> selectPage =
14                 this.commcauseElementMapper.selectPage(new Page<>(current, size), wrappers);
15         return selectPage;
16     }
复制代码

 

posted @   巴啦啦小花总  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示