Jpa实现多条件分页查询(告别组装sql)

  1. 不需要自己拼写组装sql
  2. 引用pom

    com.querydsl
    querydsl-jpa


    com.querydsl
    querydsl-apt

3.建实体类,maven 编译代后生产QOrderEntity,QOrderEntity is a Querydsl query type for OrderEntity

@Data
@DynamicInsert
@DynamicUpdate
@Entity
@Table(name = "t_order")
public class OrderEntity {

  /**
   * 主键
   */
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long id;
  /**
   * 平台订单号
   */
  @Column(name = "order_id")
  private String orderId;
  /**
   * 用户id
   */
  @Column(name = "user_id")
  private String userId;

}

4.具体demo示例

//加sql条件
List predicates = new ArrayList<>();
if (StringUtils.isNotBlank(userId)) {
    predicates.add(QOrderEntity.orderEntity.userId.eq(userId));
}
if (StringUtils.isNotBlank(orderId)) {
    predicates.add(QOrderEntity.orderEntity.orderId.eq(orderId));
}

//加sql排序
List sorts = new ArrayList<>();
sorts.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
Sort sort = new Sort(sorts);
//加sql分页
Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
Page tbOtaDeviceResults = orderDao.findAll(ExpressionUtils.allOf(predicates.toArray(new Predicate[]{})), pageable);

你可能感兴趣的:(Jpa实现多条件分页查询(告别组装sql))