Spring Data JPA仕様を使用したRESTクエリ言語
1. 概要
このチュートリアルでは、Spring Data JPAと仕様を使用してSearch/Filter REST APIを作成します。
JPA Criteriaベースのソリューションを使用して、this seriesのfirst articleでクエリ言語を検討し始めました。
つまり–why a query language?なぜなら–複雑で十分なAPIの場合–非常に単純なフィールドでリソースを検索/フィルタリングするだけでは不十分だからです。 A query language is more flexibleを使用すると、必要なリソースに正確に絞り込むことができます。
2. Userエンティティ
まず、検索APIの単純なUserエンティティから始めましょう。
@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. Specificationを使用したフィルター
それでは、問題の最も興味深い部分であるカスタムSpring Data JPASpecificationsを使用したクエリに直接取り掛かりましょう。
Specificationインターフェースを実装するUserSpecificationを作成し、pass in our own constraint to construct the actual queryに進みます。
public class UserSpecification implements Specification {
private SearchCriteria criteria;
@Override
public Predicate toPredicate
(Root root, CriteriaQuery> query, CriteriaBuilder builder) {
if (criteria.getOperation().equalsIgnoreCase(">")) {
return builder.greaterThanOrEqualTo(
root. get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase("<")) {
return builder.lessThanOrEqualTo(
root. get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase(":")) {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(
root.get(criteria.getKey()), "%" + criteria.getValue() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
return null;
}
}
ご覧のとおり–次の「SearchCriteria」クラスで表すwe create a Specification based on some simple constrains:
public class SearchCriteria {
private String key;
private String operation;
private Object value;
}
SearchCriteria実装は、制約の基本的な表現を保持します。これは、この制約に基づいて、クエリを作成します。
-
key:フィールド名–たとえば、firstName、age、…など。
-
operation:演算–たとえば、等式、より小さい、…など。
-
value:フィールド値–たとえば、john、25、…など。
もちろん、実装は単純化されており、改善することができます。しかし、それは私たちが必要とする強力で柔軟な操作のための強固な基盤です。
4. UserRepository
次へ–UserRepositoryを見てみましょう。 JpaSpecificationExecutorを拡張して、新しい仕様APIを取得するだけです。
public interface UserRepository
extends JpaRepository, JpaSpecificationExecutor {}
5. 検索クエリをテストする
それでは、新しい検索APIをテストしてみましょう。
まず、テストの実行時に準備ができるように、いくつかのユーザーを作成しましょう。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class })
@Transactional
@TransactionConfiguration
public class JPASpecificationsTest {
@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);
}
}
次に、given last nameのユーザーを見つける方法を見てみましょう。
@Test
public void givenLast_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, isIn(results));
}
次に、指定されたboth first and last nameを持つユーザーを見つける方法を見てみましょう。
@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("firstName", ":", "john"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List results = repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
注:combine Specificationsには「where」と「and」を使用しました。
次に、指定されたboth last name and minimum ageを持つユーザーを見つける方法を見てみましょう。
@Test
public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("age", ">", "25"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List results =
repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userTom, isIn(results));
assertThat(userJohn, not(isIn(results)));
}
それでは、doesn’t actually existであるUserを検索する方法を見てみましょう。
@Test
public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("firstName", ":", "Adam"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "Fox"));
List results =
repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userJohn, not(isIn(results)));
assertThat(userTom, not(isIn(results)));
}
最後に–Usergiven only part of the first nameを見つける方法を見てみましょう。
@Test
public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec =
new UserSpecification(new SearchCriteria("firstName", ":", "jo"));
List results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
6. Specificationsを組み合わせる
次へ–カスタムSpecificationsを組み合わせて複数の制約を使用し、複数の基準に従ってフィルタリングする方法を見てみましょう。
ビルダー(UserSpecificationsBuilder)を実装して、Specificationsを簡単かつ流暢に組み合わせることができます。
public class UserSpecificationsBuilder {
private final List params;
public UserSpecificationsBuilder() {
params = new ArrayList();
}
public UserSpecificationsBuilder with(String key, String operation, Object value) {
params.add(new SearchCriteria(key, operation, value));
return this;
}
public Specification build() {
if (params.size() == 0) {
return null;
}
List specs = params.stream()
.map(UserSpecification::new)
.collect(Collectors.toList());
Specification result = specs.get(0);
for (int i = 1; i < params.size(); i++) {
result = params.get(i)
.isOrPredicate()
? Specification.where(result)
.or(specs.get(i))
: Specification.where(result)
.and(specs.get(i));
}
return result;
}
}
7. UserController
最後に、この新しい永続性検索/フィルター機能とset up the REST APIを使用して、単純なsearch操作でUserControllerを作成します。
@Controller
public class UserController {
@Autowired
private UserRepository repo;
@RequestMapping(method = RequestMethod.GET, value = "/users")
@ResponseBody
public List 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 spec = builder.build();
return repo.findAll(spec);
}
}
英語以外の他のシステムをサポートするために、Patternオブジェクトを次のように変更できることに注意してください。
Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),", Pattern.UNICODE_CHARACTER_CLASS);
APIをテストするためのテストURLの例を次に示します。
http://localhost:8080/users?search=lastName:doe,age>25
そして応答:
[{
"id":2,
"firstName":"tom",
"lastName":"doe",
"email":"[email protected]",
"age":26
}]
Since the searches are split by a “,” in our Pattern example, the search terms can’t contain this character.パターンも空白と一致しません。
コンマを含む値を検索する場合は、「;」などの別の区切り文字の使用を検討できます。
別のオプションは、引用符の間の値を検索するようにパターンを変更し、検索用語からこれらを削除することです。
Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\"([^\"]+)\")");
8. 結論
このチュートリアルでは、強力なRESTクエリ言語のベースとなる単純な実装について説明しました。 Spring Data仕様をうまく利用して、APIをドメインやhave the option to handle many other types of operationsから遠ざけています。
この記事のfull implementationは、the GitHub projectにあります。これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。