基于mybatis plus增加较复杂自定义查询以及分页

作者 : admin 本文共2152个字,预计阅读时间需要6分钟 发布时间: 2024-06-16 共1人阅读

基于java技术,spring-boot和mybatis-plus搭建后台框架是现在非常流行的技术。

其中关于多表关联查询的实现相对比较复杂,在这里进行记录以供开发人员参考。

以一个系统中实际的实体类为查询为例,

T3dMaterial实体其中的fileType属性及字段,关联到类型表T3dMaterityps对象的typ_id字段

如果要实现查询T3dMaterial实体的同时也返回关联表T3dMaterityps对象的字段属性如fileTypeName。

1、修改T3dMaterial实体或者T3dMaterial实体 的Vo对象 ,在Mapper.xml 增加所关联的 第二个表对象属性fileTypeName 。


        
        
        
        
        
        
        
        
        
        
        
    

2、修改Vo对象增加属性

    private String fileTypeName;

3、在Mapper.xml增加关联查询的select定义如


        SELECT a.id,a.filename,a.file_type,a.file_type_parent,a.fileip_port,a.filepath,a.bucketname,a.create_by,a.create_time,b.typ_name
        from t3d_material a
        INNER JOIN t3d_materityps b on a.file_type=b.typ_id
        
        and id = #{et.id} 
        and a.filename LIKE CONCAT('%', #{et.filename}, '%')
        and a.file_type = #{et.fileType}
        and a.filepath LIKE CONCAT('%', #{et.filepath}, '%') 
        and a.bucketname = #{et.bucketname}
        
    

该select 的parameterType 对应T3dMaterial实体的Bo对象(根据各个框架要求,也可以是其他Bean,只要属性能对应),resultMap是第一步在Mapper.xml增加的resultMap。

该select 实现了,根据对象属性作为查询参数,同时实现了对象参数是否为null或者空的校验,实现了 LIKE 查询的典型用法如  and a.filename LIKE CONCAT(‘%’, #{et.filename}, ‘%’)

该select的where 条件中每个传入参数对象都以 et作为别名,带et.前缀。之所以et是依据com.baomidou.mybatisplus.core.toolkit 包的Constants.ENTITY=”et”

4、在 Mapper接口增加对应查询方法,增加的代码片段如下:

import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ldcc.gis.domain.T3dMaterial;
import com.ldcc.gis.domain.bo.T3dMaterialBo;
import com.ldcc.gis.domain.vo.T3dMaterialVo;

import org.apache.ibatis.annotations.Param;

Page selectList2(Page page, @Param(Constants.ENTITY) T3dMaterialBo bo);

该方法主要用到了Page对象,传入参数前面注解 @Param(Constants.ENTITY) 表示查询条件根据实体Bean构造,与Mapper.xml中的select 的parameterType 对应。

5、完成以上步骤,基本上在spring-boot和mybatis-plus框架下对于一个较复杂关联查询,并且实现分页的功能已经完成。

本案例的实际环境是基于目前也比较常用的ruoyi-vue-plus 4.X
地址: RuoYi-Vue-Plus (gitee)基于mybatis plus增加较复杂自定义查询以及分页插图https://gitee.com/JavaLionLi/RuoYi-Vue-Plus

在 Service 中调用相对比较简单

@RequiredArgsConstructor
@Service
public class T3dMaterialServiceImpl implements IT3dMaterialService {

    private final T3dMaterialMapper baseMapper;

    @Override
    public TableDataInfo queryPageAList( Page page,T3dMaterialBo bo ) {
        //LambdaQueryWrapper lqw = buildQueryWrapper(bo);
        Page result =   baseMapper.selectList2(page,bo);

//        return result;
        return TableDataInfo.build(result);
    }

该Service 调用最终以 TableDataInfo 返回,如果不是基于ruoyi-vue-plus没有该对象,可以直接返回Page ,或者封装成自己框架所需要的数据列表对象。

本站无任何商业行为
个人在线分享 » 基于mybatis plus增加较复杂自定义查询以及分页
E-->