主要依赖
org.springframework.boot
spring-boot-starter-data-jpa
这里以我最近自己瞎折腾的项目部分代码为例子(仅展示主要部分):
实体类名称(Confusion)
需要注意的是
类上+ @Entity
主键字段+ @Id
packagecn.zytao.taosir.disabuse.dao;importorg.springframework.data.jpa.repository.JpaRepository;importorg.springframework.data.jpa.repository.JpaSpecificationExecutor;importcn.zytao.taosir.common.model.disabuse.Confusion;public interface ConfusionRepository extends JpaRepository, JpaSpecificationExecutor{
}
JpaRpository这里就不多讲了,需要注意的是,同时继承JpaSpecificationExecutor
我们发现,继承该类后,可以使用相关的API
注意Specification类
通过源码可以发现这个方法,关键就是重写它了
在Service层中
@SuppressWarnings({ "deprecation", "serial"})
@Overridepublic Page findByPageAndParams(Confusion params, int pageNumber, intpageSize) {
Pageable pageable= newPageRequest(pageNumber, pageSize);
Specification confusion=new Specification() {
@Overridepublic Predicate toPredicate(Root root, CriteriaQuery>query,
CriteriaBuilder criteriaBuilder) {
Path theme = root.get("theme");return criteriaBuilder.like(theme, "%"+params.getTheme()+"%");
}
};returnconfusionRepository.findAll(confusion, pageable);
}
以上仅做参考,CriteribBuilder用于构造自定义的查询条件(即条件构造器)
通过相关的方法,我们可以采用类字符串拼接的方式,以节点把多个 criteriaBuilder 拼成一个 criteriaBuilder
之后在toPredicate方法返回即可
控制层
public JSONObject findByParamAndPage(@RequestBody Confusion confusion, int pageNumber, intpageSize) {
Page result =confusionService.findByPageAndParams(confusion, pageNumber, pageSize);
JSONObject data=newJSONObject();
data.put("content", result.getContent());
data.put("totalNums", result.getTotalElements());
data.put("totalPages",result.getTotalPages());returnActionHelper.responseOk(data);
}
因为这里我的项目使用的是分布式的一个实现方式,[email protected],自行编写
下面看看在swagger2下的效果。
原文:https://www.cnblogs.com/it-taosir/p/9874033.html