前言
為了可以
偷懶開發(fā)快速開發(fā),和減輕和前端溝通,需要找到一個可以使用實體字段動態(tài)查詢jpa撵摆,并輸出到mvc給前端對接后臺管理界面。我看了三天三夜文檔,從elasticsearch 害晦,graphsql jpa Criteria ,到 JPA specification再到specificationBuilder...
特铝,看了這么都東西后自己實現(xiàn)了一套Query language.
//隨便看看就好
窮舉查詢情況
/users?
1. 查詢id等于或name like 或 手機號like
search=id:106|name~106|mobile~106
2.查詢 16~18歲叫 lucy 的妞
search=sex:妞,age>16,age<18
3.查詢訂單狀態(tài)等于SUCCESS,CANCEL ,summary like 買了個并
orders?search=(status:SUCCESS|status:CANCEL),name~買了個并
4,雙重條件
search=((user.roles:admin|roles:tester),name~大吉)|((user.roles:admin2|roles:tester2),name~大吉)
RSQL 不搞這個了
5,starwith
search=role:ROLE_%
開始感覺自我良好。這次有個可以開源的組件了壹瘟。
- 和前端
吵了兩天商討了兩天,主要問題還是在不好轉(zhuǎn)義成URL鲫剿。之后繼續(xù)查看了. RSQL, FIQL等文件。我覺得還是用標準的東西好稻轨,所以開始我的RSQL之旅灵莲。
重點
- 需要簡單并滿足90%的查詢需求,不需要一直寫代碼殴俱。
RSQL
- 全稱RestFull Query Language.
- 就是一個可以滿足我重點要求的技術(shù)標準政冻。
- 問題:沒有大廠家實現(xiàn),只能用野雞的了线欲,怎么都好過自己寫明场。
開始
<dependency>
<groupId>cz.jirutka.rsql</groupId>
<artifactId>rsql-parser</artifactId>
<version>2.1.0</version>
</dependency>
//Repository 加入JpaSpecificationExecutor
public interface ArticleRepository extends JpaRepository<Article,String >,JpaSpecificationExecutor<Article> {
//使用
articleRepository.findAll(specification,pageable).getContent();
//添加到RestController
@GetMapping(value = "/users", produces = "application/json; charset=utf-8")
public List<User> search(@RequestParam(value = "search",required = false) String search,
@RequestParam(required = false,defaultValue = "0") Integer page,
@RequestParam(required = false,defaultValue = "20") Integer size) {
List<User> users = null;
Pageable pageable = PageRequest.of(page,size,Sort.by(
new Sort.Order(Sort.Direction.DESC, "createTime")));
if(StringUtils.isEmpty(search)){
users = userService.findAll(pageable);
}else {
Node rootNode = new RSQLParser().parse(search);
Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
users = userService.findAll(spec,pageable);
}
return users;
}
RSQL語法
RSQL expression is composed of one or more comparisons, related to each other with logical operators:
Logical AND : ; or and
Logical OR : , or or
Equal to : ==
Not equal to : !=
Less than : =lt= or <
Less than or equal to : =le= or ??
Greater than operator : =gt= or >
Greater than or equal to : =ge= or >=
In : =in=
Not in : =out=
測試
/users?search=id==1
[
{
"id": 1,
"image": null,
"name": "admin",
"signature": null,
"sex": null,
"updateTime": "2019-01-05 16:15:54",
"createTime": "2019-01-05 16:15:54"
}
]