通过mybatis-plus-join 实现mybatis plus联表查询

1、引包

  
            com.github.yulichang
            mybatis-plus-join-boot-starter
            1.4.10
        

        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.0
        

2、mapper处理:把mybaits plus的BaseMapper 改成MPJBaseMapper

@Mapper
public interface ScaleMapper extends MPJBaseMapper {
}

3、样例: 使用 MPJLambdaWrapper

  /**
     * 查询扩缩容
     * @param resourceType
     * @param status
     * @param pageSize
     * @param pageNum
     * @return
     */
    public IPage getScaleResource(String resourceType, Integer status, Date startTime, Date endTime,  Long pageSize, Long pageNum){
        log.info("查询扩缩容,resourceType:{}, status:{},  startTime:{}, endTime:{},  pageSize:{}, pageNum:{}", resourceType, status, startTime, endTime,  pageSize, pageNum);
        MPJLambdaWrapper queryWrapper = new MPJLambdaWrapper<>();
        Page page = new Page<>(pageNum, pageSize);
        if(Objects.nonNull(resourceType)){
            queryWrapper.eq(Scale::getResourceType, resourceType);
        }
        if(Objects.nonNull(status)){
            queryWrapper.eq(Scale::getStatus, status);
        }
        if(Objects.nonNull(startTime)){
            queryWrapper.ge(Scale::getCreatedAt, startTime);
        }
        if(Objects.nonNull(endTime)){
            queryWrapper.le(Scale::getCreatedAt, endTime);
        }
        queryWrapper.leftJoin(Strategy.class, Strategy::getId, Scale::getStrategyId);
        queryWrapper.selectAll(Scale.class);
        queryWrapper.selectAs(Strategy::getName, Scale::getStrategyName);
        queryWrapper.orderByDesc(Scale::getCreatedAt);
        IPage result = scaleMapper.selectPage(page, queryWrapper);
        log.info("查询扩缩容结果:{}", JSON.toJSON(result));
        return result;
    }

样例生成的sql: 

SELECT
	t.id,
	t.resource_id,
	t.resource_name,
	t.resource_type,
	t.pod_id,
	t.strategy_id,
	t.contents,
	t.STATUS,
	t.created_at,
	t.updated_at,
	t.business_id,
	t.business_name,
	t.ip,
	t1.NAME AS strategyName 
FROM
	comp_sta_scale_t t
	LEFT JOIN comp_sta_strategy_t t1 ON ( t1.id = t.strategy_id ) 
ORDER BY
	t.created_at DESC 

4、github网址及mybatis-plus-join网址

https://github.com/yulichang/mybatis-plus-join
https://mybatisplusjoin.com/pages/quickstart/js.html

你可能感兴趣的:(mybatis)