<div>
<a class="article-series-header" href="javascript:void(0);">該文章是系列的一部分</a>
<div>
<div>
• 使用 Spring 和 JPA Criteria 的 REST 查詢語言
<br>
<div>
• 使用 Spring Data JPA Specifications 的 REST 查詢語言(當前文章)
</div>
• 使用 Spring Data JPA 和 Querydsl 的 REST 查詢語言
<br>
• REST 查詢語言 – 高級搜索操作
<br>
• REST 查詢語言 – 實現 OR 操作
<br>
• REST 查詢語言與 RSQL
<br>
• REST 查詢語言與 Querydsl Web 支持
<br>
</div>
<!-- end of article series inner -->
</div>
<!-- .article-series-links -->
</div>
<!-- end of article series section -->
1. 概述
在本教程中,我們將使用 Spring Data JPA 和 Specifications 構建一個 搜索/過濾 REST API。
我們在本系列的第一篇文章中探討了查詢語言,並使用了基於 JPA Criteria 的解決方案。
因此,為什麼需要查詢語言? 因為僅僅通過簡單的字段搜索/過濾我們的資源對於過於複雜的 API 來説已經不夠用了。 查詢語言更具靈活性 並且允許我們過濾出我們需要的資源。
2. <em User 實體
首先,讓我們從一個簡單的 <em User 實體開始,用於我們的搜索 API:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private int age;
// standard getters and setters
}3. 使用 規範 進行過濾
現在我們直接進入問題的最有趣的部分:使用自定義的 Spring Data JPA 規範 進行查詢。
我們將創建一個 UserSpecification,該類實現 Specification 接口,並且我們將傳入我們自己的約束條件,以構建實際的查詢:
public class UserSpecification implements Specification<User> {
private SearchCriteria criteria;
@Override
public Predicate toPredicate
(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (criteria.getOperation().equalsIgnoreCase(">")) {
return builder.greaterThanOrEqualTo(
root.<String> get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase("<")) {
return builder.lessThanOrEqualTo(
root.<String> get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase(":")) {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(
root.<String>get(criteria.getKey()), "%" + criteria.getValue() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
return null;
}
}我們可以看到,我們創建一個基於一些簡單約束的 規範,這些約束我們用下面的 SearchCriteria 類來表示:
public class SearchCriteria {
private String key;
private String operation;
private Object value;
}SearchCriteria 實現持有基本約束的表示,並且基於此約束我們構建查詢:
- key:字段名稱,例如firstName、age等。
- operation:操作,例如等於、小於等。
- value:字段值,例如john、25等。
當然,實現方式比較簡單,可以改進。但是,它為我們所需的強大且靈活的操作提供了一個堅實的基礎。
4. UserRepository
接下來,我們來查看一下 UserRepository。
我們只是將 JpaSpecificationExecutor 擴展以獲取新的 Specification API:
public interface UserRepository
extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {}5. 測試搜索查詢
現在讓我們測試新的搜索 API。
首先,讓我們創建一些用户,以便在測試運行時準備好他們:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class })
@Transactional
@TransactionConfiguration
public class JPASpecificationIntegrationTest {
@Autowired
private UserRepository repository;
private User userJohn;
private User userTom;
@Before
public void init() {
userJohn = new User();
userJohn.setFirstName("John");
userJohn.setLastName("Doe");
userJohn.setEmail("[email protected]");
userJohn.setAge(22);
repository.save(userJohn);
userTom = new User();
userTom.setFirstName("Tom");
userTom.setLastName("Doe");
userTom.setEmail("[email protected]");
userTom.setAge(26);
repository.save(userTom);
}
}接下來,讓我們看看如何查找姓氏為指定姓氏的用户:
@Test
public void givenLast_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List<User> results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, isIn(results));
}現在我們將查找一個具有給定名和姓氏的用户:
@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("firstName", ":", "john"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List<User> results = repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}注意:我們使用了 where 和 and 來組合規範。
接下來,讓我們找到一個滿足給定 姓氏和最小年齡的用户:
@Test
public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("age", ">", "25"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List<User> results =
repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userTom, isIn(results));
assertThat(userJohn, not(isIn(results)));
}現在我們將看看如何搜索一個不存在的User:
@Test
public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("firstName", ":", "Adam"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "Fox"));
List<User> results =
repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userJohn, not(isIn(results)));
assertThat(userTom, not(isIn(results)));
}最後,我們將找到一個User僅提供了部分姓名的用户:
@Test
public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec =
new UserSpecification(new SearchCriteria("firstName", ":", "jo"));
List<User> results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}6. 組合規範
接下來,讓我們看看如何將我們的自定義 規範 組合起來,以使用多個約束條件和根據多個標準進行過濾。
我們將實現一個構建器——UserSpecificationsBuilder——以便輕鬆、流暢地組合 規範。但是,在繼續之前,讓我們先查看一下——SpecSearchCriteria 對象:
public class SpecSearchCriteria {
private String key;
private SearchOperation operation;
private Object value;
private boolean orPredicate;
public boolean isOrPredicate() {
return orPredicate;
}
}public class UserSpecificationsBuilder {
private final List<SpecSearchCriteria> params;
public UserSpecificationsBuilder() {
params = new ArrayList<>();
}
public final UserSpecificationsBuilder with(String key, String operation, Object value,
String prefix, String suffix) {
return with(null, key, operation, value, prefix, suffix);
}
public final UserSpecificationsBuilder with(String orPredicate, String key, String operation,
Object value, String prefix, String suffix) {
SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0));
if (op != null) {
if (op == SearchOperation.EQUALITY) { // the operation may be complex operation
boolean startWithAsterisk = prefix != null &&
prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX);
boolean endWithAsterisk = suffix != null &&
suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX);
if (startWithAsterisk && endWithAsterisk) {
op = SearchOperation.CONTAINS;
} else if (startWithAsterisk) {
op = SearchOperation.ENDS_WITH;
} else if (endWithAsterisk) {
op = SearchOperation.STARTS_WITH;
}
}
params.add(new SpecSearchCriteria(orPredicate, key, op, value));
}
return this;
}
public Specification build() {
if (params.size() == 0)
return null;
Specification result = new UserSpecification(params.get(0));
for (int i = 1; i < params.size(); i++) {
result = params.get(i).isOrPredicate()
? Specification.where(result).or(new UserSpecification(params.get(i)))
: Specification.where(result).and(new UserSpecification(params.get(i)));
}
return result;
}
}7. UserController
最後,讓我們利用新的持久化搜索/過濾功能,並設置 REST API,通過創建UserController,並實現一個簡單的搜索操作:
@Controller
public class UserController {
@Autowired
private UserRepository repo;
@RequestMapping(method = RequestMethod.GET, value = "/users")
@ResponseBody
public List<User> search(@RequestParam(value = "search") String search) {
UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
}
Specification<User> spec = builder.build();
return repo.findAll(spec);
}
}請注意,為了支持其他非英語系統,Pattern 對象可以被修改:
Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),", Pattern.UNICODE_CHARACTER_CLASS);以下是一個用於測試 API 的測試 URL:
http://localhost:8082/spring-rest-query-language/auth/users?search=lastName:doe,age>25以下是響應:
[{
"id":2,
"firstName":"tom",
"lastName":"doe",
"email":"[email protected]",
"age":26
}]由於搜索項通過“,”在我們的 Pattern 示例中進行分割,因此搜索詞不能包含該字符。 該模式也不匹配空格。
如果我們想搜索包含逗號的值,可以考慮使用不同的分隔符,如“;”。
另一種選擇是更改模式以搜索在引號之間的值,然後從搜索詞中刪除這些引號:
Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\"([^\"]+)\")");8. 結論
本文介紹了可作為強大 REST 查詢語言基礎的簡單實現。
我們充分利用了 Spring Data Specifications,以確保 API 與領域分離,並具備處理多種操作的選項。