實體為我們的搜索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. The 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 與領域分離,並提供處理多種操作的選項。
下一條 »
REST Query Language with Spring Data JPA and Querydsl
« 上一篇
REST Query Language with Spring and JPA Criteria
0 位用戶收藏了這個故事!