RESTクエリ言語-高度な検索操作
1. 概要
この記事では、the seriesのthe previous partsで開発したRESTクエリ言語をinclude more search operationsに拡張します。
次の操作をサポートするようになりました:平等、否定、大なり、小なり、次で始まる、次で終わる、含む、いいね。
JPA基準、Spring Data JPA仕様、およびQueryDSLの3つの実装を検討したことに注意してください。この記事の仕様は、私たちの業務を表現するためのクリーンで柔軟な方法であるため、先に進めます。
2. SearchOperationenum
まず、列挙型を使用して、サポートされているさまざまな検索操作のより適切な表現を定義することから始めましょう。
public enum SearchOperation {
EQUALITY, NEGATION, GREATER_THAN, LESS_THAN, LIKE, STARTS_WITH, ENDS_WITH, CONTAINS;
public static final String[] SIMPLE_OPERATION_SET = { ":", "!", ">", "<", "~" };
public static SearchOperation getSimpleOperation(char input) {
switch (input) {
case ':':
return EQUALITY;
case '!':
return NEGATION;
case '>':
return GREATER_THAN;
case '<':
return LESS_THAN;
case '~':
return LIKE;
default:
return null;
}
}
}
次の2つの操作セットがあります。
1. Simple –1文字で表すことができます。
-
等式:コロン(:)で表されます
-
否定:感嘆符(!)で表されます
-
大なり記号:(>)で表されます
-
より小さい:(<)で表されます
-
のように:チルダで表される(~)
2. Complex –表現するには複数の文字が必要です。
-
で始まる:(=prefix*)で表される
-
で終わる:(=*suffix)で表される
-
含まれるもの:(=*substring*)で表される
また、新しいSearchOperationを使用するように、SearchCriteriaクラスを変更する必要があります。
public class SearchCriteria {
private String key;
private SearchOperation operation;
private Object value;
}
3. UserSpecificationを変更する
では、新しくサポートされた操作をUserSpecificationの実装に含めましょう。
public class UserSpecification implements Specification {
private SearchCriteria criteria;
@Override
public Predicate toPredicate(
Root root, CriteriaQuery> query, CriteriaBuilder builder) {
switch (criteria.getOperation()) {
case EQUALITY:
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
case NEGATION:
return builder.notEqual(root.get(criteria.getKey()), criteria.getValue());
case GREATER_THAN:
return builder.greaterThan(root. get(
criteria.getKey()), criteria.getValue().toString());
case LESS_THAN:
return builder.lessThan(root. get(
criteria.getKey()), criteria.getValue().toString());
case LIKE:
return builder.like(root. get(
criteria.getKey()), criteria.getValue().toString());
case STARTS_WITH:
return builder.like(root. get(criteria.getKey()), criteria.getValue() + "%");
case ENDS_WITH:
return builder.like(root. get(criteria.getKey()), "%" + criteria.getValue());
case CONTAINS:
return builder.like(root. get(
criteria.getKey()), "%" + criteria.getValue() + "%");
default:
return null;
}
}
}
4. 持続性テスト
次に、新しい検索操作を永続性レベルでテストしましょう。
4.1. テストの同等性
次の例では、ユーザーby their first and last nameを検索します。
@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec = new UserSpecification(
new SearchCriteria("firstName", SearchOperation.EQUALITY, "john"));
UserSpecification spec1 = new UserSpecification(
new SearchCriteria("lastName", SearchOperation.EQUALITY, "doe"));
List results = repository.findAll(Specification.where(spec).and(spec1));
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
4.2. テストの否定
次に、their first name not “john”で次のようなユーザーを検索しましょう。
@Test
public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec = new UserSpecification(
new SearchCriteria("firstName", SearchOperation.NEGATION, "john"));
List results = repository.findAll(Specification.where(spec));
assertThat(userTom, isIn(results));
assertThat(userJohn, not(isIn(results)));
}
4.3. 大なり記号をテストする
次へ–age greater than “25”のユーザーを検索します。
@Test
public void givenMinAge_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec = new UserSpecification(
new SearchCriteria("age", SearchOperation.GREATER_THAN, "25"));
List results = repository.findAll(Specification.where(spec));
assertThat(userTom, isIn(results));
assertThat(userJohn, not(isIn(results)));
}
4.4. テストは
次へ–their first name starting with “jo”のユーザー:
@Test
public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec = new UserSpecification(
new SearchCriteria("firstName", SearchOperation.STARTS_WITH, "jo"));
List results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
4.5. テストはで終了します
次に、their first name ending with “n”のユーザーを検索します。
@Test
public void givenFirstNameSuffix_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec = new UserSpecification(
new SearchCriteria("firstName", SearchOperation.ENDS_WITH, "n"));
List results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
4.6. テストに含まれるもの
次に、their first name containing “oh”のユーザーを検索します。
@Test
public void givenFirstNameSubstring_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec = new UserSpecification(
new SearchCriteria("firstName", SearchOperation.CONTAINS, "oh"));
List results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
4.7. テスト範囲
最後に、ages between “20” and “25”のユーザーを検索します。
@Test
public void givenAgeRange_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec = new UserSpecification(
new SearchCriteria("age", SearchOperation.GREATER_THAN, "20"));
UserSpecification spec1 = new UserSpecification(
new SearchCriteria("age", SearchOperation.LESS_THAN, "25"));
List results = repository.findAll(Specification.where(spec).and(spec1));
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
5. UserSpecificationBuilder
永続性が完了してテストされたので、次にWebレイヤーに注目しましょう。
前の記事からincorporate the new new search operationsへのUserSpecificationBuilder実装の上に構築します。
public class UserSpecificationsBuilder {
private List params;
public UserSpecificationsBuilder with(
String key, String operation, Object value, String prefix, String suffix) {
SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0));
if (op != null) {
if (op == SearchOperation.EQUALITY) {
boolean startWithAsterisk = prefix.contains("*");
boolean endWithAsterisk = suffix.contains("*");
if (startWithAsterisk && endWithAsterisk) {
op = SearchOperation.CONTAINS;
} else if (startWithAsterisk) {
op = SearchOperation.ENDS_WITH;
} else if (endWithAsterisk) {
op = SearchOperation.STARTS_WITH;
}
}
params.add(new SearchCriteria(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;
}
}
6. UserController
次に–UserControllerを正しくparse the new operationsに変更する必要があります。
@RequestMapping(method = RequestMethod.GET, value = "/users")
@ResponseBody
public List findAllBySpecification(@RequestParam(value = "search") String search) {
UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
Pattern pattern = Pattern.compile(
"(\\w+?)(" + operationSetExper + ")(\p{Punct}?)(\\w+?)(\p{Punct}?),");
Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
builder.with(
matcher.group(1),
matcher.group(2),
matcher.group(4),
matcher.group(3),
matcher.group(5));
}
Specification spec = builder.build();
return dao.findAll(spec);
}
これで、APIをヒットし、条件の任意の組み合わせで正しい結果を取得できます。 例–クエリ言語でAPIを使用すると、複雑な操作はどのようになりますか。
http://localhost:8080/users?search=firstName:jo*,age<25
そして応答:
[{
"id":1,
"firstName":"john",
"lastName":"doe",
"email":"[email protected]",
"age":24
}]
7. SearchAPIのテスト
最後に、一連のAPIテストを作成して、APIが適切に機能することを確認しましょう。
テストの簡単な構成とデータの初期化から始めます。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = { ConfigTest.class, PersistenceConfig.class },
loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("test")
public class JPASpecificationLiveTest {
@Autowired
private UserRepository repository;
private User userJohn;
private User userTom;
private final String URL_PREFIX = "http://localhost:8080/users?search=";
@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);
}
private RequestSpecification givenAuth() {
return RestAssured.given().auth()
.preemptive()
.basic("username", "password");
}
}
7.1. テストの同等性
まず、the first name “john” and last name “doe“でユーザーを検索しましょう。
@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
Response response = givenAuth().get(URL_PREFIX + "firstName:john,lastName:doe");
String result = response.body().asString();
assertTrue(result.contains(userJohn.getEmail()));
assertFalse(result.contains(userTom.getEmail()));
}
7.2. テストの否定
今–their first name isn’t “john”のときにユーザーを検索します:
@Test
public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() {
Response response = givenAuth().get(URL_PREFIX + "firstName!john");
String result = response.body().asString();
assertTrue(result.contains(userTom.getEmail()));
assertFalse(result.contains(userJohn.getEmail()));
}
7.3. 大なり記号をテストする
次へ–age greater than “25”のユーザーを探します:
@Test
public void givenMinAge_whenGettingListOfUsers_thenCorrect() {
Response response = givenAuth().get(URL_PREFIX + "age>25");
String result = response.body().asString();
assertTrue(result.contains(userTom.getEmail()));
assertFalse(result.contains(userJohn.getEmail()));
}
7.4. テストは
次へ–their first name starting with “jo”のユーザー:
@Test
public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() {
Response response = givenAuth().get(URL_PREFIX + "firstName:jo*");
String result = response.body().asString();
assertTrue(result.contains(userJohn.getEmail()));
assertFalse(result.contains(userTom.getEmail()));
}
7.5. テストはで終了します
現在–their first name ending with “n”のユーザー:
@Test
public void givenFirstNameSuffix_whenGettingListOfUsers_thenCorrect() {
Response response = givenAuth().get(URL_PREFIX + "firstName:*n");
String result = response.body().asString();
assertTrue(result.contains(userJohn.getEmail()));
assertFalse(result.contains(userTom.getEmail()));
}
7.6. テストに含まれるもの
次に、their first name containing “oh”のユーザーを検索します。
@Test
public void givenFirstNameSubstring_whenGettingListOfUsers_thenCorrect() {
Response response = givenAuth().get(URL_PREFIX + "firstName:*oh*");
String result = response.body().asString();
assertTrue(result.contains(userJohn.getEmail()));
assertFalse(result.contains(userTom.getEmail()));
}
7.7. テスト範囲
最後に、ages between “20” and “25”のユーザーを検索します。
@Test
public void givenAgeRange_whenGettingListOfUsers_thenCorrect() {
Response response = givenAuth().get(URL_PREFIX + "age>20,age<25");
String result = response.body().asString();
assertTrue(result.contains(userJohn.getEmail()));
assertFalse(result.contains(userTom.getEmail()));
}
8. 結論
この記事では、REST Search APIのクエリ言語をa mature, tested, production-grade implementationに転送しました。 現在、さまざまな操作と制約をサポートしています。これにより、データセットをエレガントに横断し、探している正確なリソースに簡単にアクセスできるようになります。
この記事のfull implementationは、the GitHub projectにあります。これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。