Spring Data JPA 二:实现多表关联分页查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27376871/article/details/82662845

最近在对JPA的使用过程中发现对于单表的操作很是方便,但是当设计到多表联查的时候就需要有一些特殊的操作了。

项目中有一个场景是后台需要做一个分页的列表查询,所需要的数据分散在两张表中,如果是用mybatis的话直接定义resultMap,然后手写SQL就可以了。而在JPA中就需要用到JPQL了。

首先定义一下各个对象之间的关系

实体 GxOrderDO :订单。

实体 GxOrderDetailDO:订单详情。

实体 GxOrderInfoRsp:分装的分页返回对象。

其中的GxOrderDO和GxOrderDetailDO通过orderId字段做两张表的关联。

创建一个对象用来封装返回的结果集:

GxOrderInfoRsp.java:

public class GxOrderInfoRsp implements Serializable{
    /**
     * 订单ID
     */
    private String orderId;
    /**
     * 订单状态
     */
    private Integer orderStatus;
    /**
     * 订单类型
     */
    private Integer orderType;
    /**
     * 订单支付金额
     */
    private BigDecimal orderAmount;
    /**
     * 订单渠道(设备)类型 
     */
    private Integer orderChannel;

    public GxOrderInfoRsp(String orderId, Integer orderStatus, Integer orderType,         
                          BigDecimal orderAmount, Integer orderChannel) {
        this.orderId = orderId;
        this.orderStatus = orderStatus;
        this.orderType = orderType;
        this.orderAmount = orderAmount;
        this.orderChannel = orderChannel;
        
    }

Repository:

@Query("SELECT new com.app.domain.GxOrderInfoRsp(r.orderId, r.orderStatus, r.orderType, rd.orderAmount, rd.orderChannel)" +
        " FROM GxOrderDO r, GxOrderDetailDO rd WHERE r.orderId = rd.orderId and ( r.orderId=:#{#customer.orderId} or :#{#customer.orderId} is null)   ")
Page<GxOrderInfoRsp>  findOrderPage(@Param("customer") GxOrderDO customer,Pageable pageable);

注意:@Query中new的对象的参数顺序要和构造方法的参数顺序一致

r.orderId=:#{#customer.orderId} or :#{#customer.orderId} is null) 
这种是做个非空判断,如果是空,就跳过这个条件,不执行。
这里面用到了Spring Data JPA @Query定义中的SpEL特性

Service:

Pageable pageable = new PageRequest(0,3, Sort.Direction.DESC,"createTime");

文章参考:

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

https://blog.csdn.net/moshowgame/article/details/80672617

猜你喜欢

转载自blog.csdn.net/qq_27376871/article/details/82662845