JPA的分页查询确实使用起来确实很简单,但理解起来有点困难,此处只是实现JPA分页的代码块。
定义实体类:
@Entity
@Table(name = "t_pub_info")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class InfoPO implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name ="name")
private String name;
@Column(name = "priority")
private String priority;
@Column(name = "pub_time")
private Date pubTime;
@Column(name = "depict")
private String depict;
@Column(name ="city_id")
private Long cityId;
@Column(name = "status")
private String status;
Getter...
Setter...
}
定义DAO:
public interface InfoDao extends JpaRepository<InfoPO, Long>, JpaSpecificationExecutor<InfoPO> {
}
定义接口:
@SuppressWarnings(value = "unused")
@RestController
@RequestMapping(value = "/info")
public class InfoController {
@Autowired
InfoService infoService;
@GetMapping(value = "/list")
Object queryInfoList(@RequestParam(value = "pageNo", required = false, defaultValue = "0") Integer pageNo,
@RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize,
@RequestParam(value = "status", required = false) String status,
@RequestParam(value = "priority", required = false) String priority,
@RequestHeader("city_id")Integer cityId) {
return infoService.queryInfoList(pageNo, pageSize, priority,cityId,String status);
}
}
定义service
public interface InfoService {
Object queryinfoList(Integer pageNo, Integer pageSize, String priority,Integer cityId,String status);
}
实现service
@Service
public class InfoServiceImpl implements InfoService {
protected static final int PAGE_SIZE = 5;
@Autowired
InfoDao infoDao;
public Object queryInfoList(Integer pageNo, Integer pageSize, String priority,Integer cityId,String status) {
//验证city_id
if(cityId == null){
throw new Exception("city id necessary");
}
Integer currentPage = pageNo == null ? 0 : pageNo;
Page<InfoPO> page = infoDao.findAll((Root<InfoPO> root, CriteriaQuery<?> cq, CriteriaBuilder cb) -> {
//添加分页筛选条件
List<Predicate> predicates = new ArrayList<>();
if (priority != null) {
predicates.add(cb.equal(root.get("priority"), priority));
}
if (status != null) {
String statusName = status;
if (StringUtils.isNotBlank(statusName)) {
predicates.add(cb.equal(root.get("status"), statusName));
}
}
if (cityId != null) {
predicates.add(cb.equal(root.get("cityId"), cityId));
}
return cb.and(predicates.toArray(new Predicate[]{}));
}, new PageRequest(currentPage, pageSize, new Sort(Sort.Direction.DESC, "pubTime")));
//获取页面数据以及分页数据
List<InfoPO> infos = page.getContent();
Integer totalPage = page.getTotalPages();
Long totalElement = page.getTotalElements();
return infos;
}
}
github上有我更多的笔记:Raray-chuan (兮川) · GitHub,欢迎stars与following,如果有问题可以在issue中向我咨询
关注我的公众号,获取更多关于后端、大数据的知识
版权声明:本文为zc_ad原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。