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());
发布了36 篇原创文章 · 获赞 134 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u011177064/article/details/104869351