Mybatis Plus 自定义SQL+多表查询结果+分页

关于Mybatis plus的 基本使用就不赘述了。

入门请移步:https://mybatis.plus/guide/

 

我只是记录一下"自定义SQL+多表查询结果+分页"情况下,怎样使用

环境: SpringBoot 2.1  + Mybatis Plus 3.1.0

需要配置mybatis plus的分页器



@Configuration
public class MyBatisPlusConfig {
    
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

}

自定义Sql 直接写在Mapper接口方法上,使用了 @Select 注解

该Sql涉及了3张表, 返回结果是两个表的字段组合而成,我这里新建了一个普通Java对象(即Product)来接收。

@Select("<script>"
+ " select tp.*,tpt.name as typeName "
+ " from jfcloud_product tp left join jfcloud_product_type_ref ref on tp.id=ref.product_id"
+ " left join jfcloud_product_type tpt on ref.type_id = tpt.id"
+ " where 1=1"
+ " and tp.is_delete=0"
+ " <if test=\"q.typeId != null\">and tpt.id = #{q.typeId} </if>"
+ " order by tp.create_time desc"
+ "</script>")
IPage<Product> getProductPage(IPage<Product> page,@Param("q") ProductQuery query);

参数列表:

page 是 mybatis plus 提供的分页对象,里面的泛型填入 我自定义的这个多表字段的实体。

query 是自定义实体,里面是需要用到的查询参数,用@Param 定义了别名"q",在Sql中可以以 #{q.xxx} 使用

两个参数顺序最好按照我上面这样,跟踪了一下源码,如果参数调换位置,mybatis plus在做返回数据转化时会抛异常

具体使用:

ProductQuery query = new ProductQuery();
query.setTypeId(1l);
		
Page<Product> page = new Page<>(1,10);
		
IPage<Product> datas = productMapper.getProductPage(page,query);
		
		
System.out.println("总记录:"+datas.getTotal());
System.out.println("总页数:"+datas.getPages());
System.out.println("数据:"+datas.getRecords());

 

  • 9
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值