使用springboot jpa完成复杂的分页查询

it2023-09-14  77

使用springboot jpa完成复杂的分页查询

贴上数据表

贴上实体类

package com.imooc.mmal.pojo; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.io.Serializable; import java.time.LocalDate; /** * (MallProduct)实体类 * * @author bin.zong * @since 2020-09-04 11:31:18 */ @Entity(name = "mall_product") @Data public class MallProduct implements Serializable { private static final long serialVersionUID = 666816867179765417L; /** * 商品id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 分类id,对应mall_category表的主键 */ private Integer categoryId; /** * 商品名称 */ private String name; /** * 商品副标题 */ private String subtitle; /** * 产品主图,url相对地址 */ private String mainImage; /** * 图片地址,json格式,扩展用 */ private String subImages; /** * 商品详情 */ private String detail; /** * 价格,单位-元保留两位小数 */ private Double price; /** * 库存数量 */ private Integer stock; /** * 商品状态.1-在售 2-下架 3-删除 */ private Integer status; /** * 创建时间 */ private LocalDate createTime; /** * 更新时间 */ private LocalDate updateTime; }

分页的时候要判断state等于1进行展示 在这里我并不想写sql语句,所以可以使用Example对象来帮住我们完成 首先创建Sort对象进行排序 之后将Sort对象扔到Page对象 在创建Example对象 创建实体类对象 贴上代码

MallProduct product=new MallProduct(); product.setStatus(MallProductEnum.IN_STOCK.getCode()); Sort sort = new Sort(Sort.Direction.DESC, "id"); Pageable pageable = PageRequest.of(pageNum, pageSize, sort); Example<MallProduct> example=Example.of(product); List<MallProduct> content = mallProductDao.findAll(example, pageable).getContent(); log.info("content",content);

查看一下控制台日志

Hibernate: select mallproduc0_.id as id1_4_, mallproduc0_.category_id as category2_4_, mallproduc0_.create_time as create_t3_4_, mallproduc0_.detail as detail4_4_, mallproduc0_.main_image as main_ima5_4_, mallproduc0_.name as name6_4_, mallproduc0_.price as price7_4_, mallproduc0_.status as status8_4_, mallproduc0_.stock as stock9_4_, mallproduc0_.sub_images as sub_ima10_4_, mallproduc0_.subtitle as subtitl11_4_, mallproduc0_.update_time as update_12_4_ from mall_product mallproduc0_ where mallproduc0_.status=1 order by mallproduc0_.id desc limit ?, ? Hibernate: select count(mallproduc0_.id) as col_0_0_ from mall_product mallproduc0_ where mallproduc0_.status=1

查看一下结果

最新回复(0)