SpringBoot 中 Jpa PageRequest 分頁 + Example 多參數 單表查詢
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
配置
spring:
#通用的數據源配置
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/main?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: root
jpa:
#這個參數是在建表的時候,將默認的存儲引擎切換爲 InnoDB 用的
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
#配置在日誌中打印出執行的 SQL 語句信息。
show-sql: true
hibernate:
#配置指明在程序啓動的時候要刪除並且創建實體類對應的表
# 第一次簡表 create 後面用 update 不然每次重啓工程會刪除表並新建。
# ddl-auto: create
ddl-auto: update
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
pojo
@Data
@Entity(name = "circuitConfig")
public class CircuitConfig {
@Id
@GeneratedValue(strategy = GenerationType.AUTO) //主鍵自動增長
public int id;
@NotEmpty(message = "cjrId 不能爲空")
@Column(length = 200)
public String cjrId;
@NotEmpty(message = "syrId 不能爲空")
@Column(length = 200)
public String syrId;
@NotEmpty(message = "url 不能爲空")
public String url;
/**
* 截取後的url
*/
@JsonIgnore
@Column(length = 200)
public String suBurl;
@NotEmpty(message = "method 不能爲空")
public String method;
/**
* 請求方式 字符串還是 json
* 1 表示 請求方式是 json
* 0 表示 請求方式是 text
*/
@NotNull(message = "contype 不能爲空")
@Column(length = 1)
public Integer contype;
/**
* 1 表示 開票流程配置
* 0 表示 其他配置
*/
@NotNull(message = "type 不能爲空")
@Column(length = 1)
public Integer type;
public Date cjsj;
}
dao
@Repository
public interface CircuitConfigDao extends JpaRepository<CircuitConfig,Integer> {
}
使用 PageRequest 進行分頁查詢
JPA中的接口
根據參數查詢信息 Example 參數查詢匹配器
可以使用 ExampleMatcher 匹配器 進行參數匹配
ExampleMatcher
:ExampleMatcher攜帶有關如何匹配特定字段的詳細信息,相當於匹配條件。
Example
:由Probe和ExampleMatcher組成,用於查詢。
缺點
屬性不支持嵌套或者分組約束,比如這樣的查詢 firstname = ?0 or (firstname = ?1 and lastname = ?2)
靈活匹配只支持字符串類型,其他類型只支持精確匹配
創建匹配器
<S extends T> List<S> findAll(Example<S> var1);
<S extends T> List<S> findAll(Example<S> var1, Sort var2);
分頁查詢接口
封裝返回結果類
分頁查詢 + 字符串匹配查詢
/**
* 分頁查詢
*
* @param circuitConfig 查詢條件
* @return 流程配置數據
*/
public ReturnMessage getListWithCriteria(PageRequestForCirVo<CircuitConfig> circuitConfig) {
CircuitConfig object = circuitConfig.getObject();
log.info("查詢條件爲 {} 頁碼 {} , 每頁數量 {} ", object, circuitConfig.getPage(), circuitConfig.getPageSize());
if (circuitConfig.getPage() < 1) {
circuitConfig.setPage(1);
}
if (circuitConfig.getPageSize() < 1) {
circuitConfig.setPageSize(10);
}
//ExampleMatcher.GenericPropertyMatchers.startsWith() 模糊查詢匹配開頭,即{username}%
//ExampleMatcher.GenericPropertyMatchers.contains()) 全部模糊查詢,即%{address}%
//ExampleMatcher.GenericPropertyMatchers.contains() 全部模糊查詢,即%{address}%
Example<CircuitConfig> example = null;
Pageable pageable = null;
Page<CircuitConfig> listWithCriteria = null;
if (object != null) {
//查詢條件
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("contype", ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("type", ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("cjrId", ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("syrId", ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("url", ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("suBurl", ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("method", ExampleMatcher.GenericPropertyMatchers.contains())
//忽略字段,即不管password是什麼值都不加入查詢條件
.withIgnorePaths("cjsj")
/*.withIgnorePaths("contype")
.withIgnorePaths("type")*/
//,需要忽略掉
.withIgnorePaths("id");
example = Example.of(object, matcher);
//分頁數據
pageable = new PageRequest(circuitConfig.getPage() - 1, circuitConfig.getPageSize(), Sort.DEFAULT_DIRECTION, "id");
//查詢
listWithCriteria = circuitConfigDao.findAll(example, pageable);
} else {
pageable = new PageRequest(circuitConfig.getPage() - 1, 10, Sort.Direction.ASC, "id");
listWithCriteria = circuitConfigDao.findAll(pageable);
}
List<CircuitConfig> content = listWithCriteria.getContent();
//返回空
if (content == null || content.size() == 0) {
log.info(" 暫無數據 ");
return new ReturnMessage(CodeMsgEnum.NOT_DATA.getCode(), CodeMsgEnum.NOT_DATA.getMsg());
}
//查詢總數
long total = mongoTemplate.count(query,CircuitConfig.class);
//包裝返回結果
PageImpl<CircuitConfig> emptyPage = new PageImpl<>(content, pageable, total);
log.info(" 返回結果爲 : {} ",JSON.toJSONString(emptyPage));
return new ReturnMessage(CodeMsgEnum.OK.getCode(), CodeMsgEnum.OK.getMsg(), emptyPage);
}
返回結果
{
"code": 0,
"msg": "成功",
"data": {
"content": [
{
"id": 1,
"cjrId": "1",
"syrId": "12",
"url": "http://127.0.0.1:8080/api/template/xx",
"method": "12",
"contype": 1,
"type": 1,
"cjsj": "2020-03-10 08:00:00"
},
{
"id": 2,
"cjrId": "1",
"syrId": "12",
"url": "http://127.0.0.1:8080/api/template/xxxx",
"method": "12",
"contype": 1,
"type": 1,
"cjsj": "2020-03-10 08:00:00"
}
],
"last": true,
"totalPages": 1,
"totalElements": 2,
"number": 0,
"size": 6, // pageSize
"sort": [
{
"direction": "ASC",
"property": "id",
"ignoreCase": false,
"nullHandling": "NATIVE",
"ascending": true,
"descending": false
}
],
"first": true,
"numberOfElements": 2
}
}