Querydsl WebサポートのあるRESTクエリ言語

Querydsl Webサポートを使用したRESTクエリ言語

1. 概要

このクイックチュートリアルでは、Spring Data QuerydslWebサポートについて説明します。

これは、the main REST Query Language seriesで焦点を当てた他のすべての方法に代わる興味深い方法です。

2. Maven構成

まず、Mavenの構成から始めましょう。


    org.springframework.boot
    spring-boot-starter-parent
    1.3.0.RELEASE



    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.data
        spring-data-commons
    
    
        com.mysema.querydsl
        querydsl-apt
        ${querydsl.version}
    
    
        com.mysema.querydsl
        querydsl-jpa
        ${querydsl.version}
    
...

Querydsl Webサポートは1.11以降spring-data-commonsで利用可能であることに注意してください

3. ユーザーリポジトリ

次に、リポジトリを見てみましょう。

public interface UserRepository extends
  JpaRepository, QueryDslPredicateExecutor, QuerydslBinderCustomizer {
    @Override
    default public void customize(QuerydslBindings bindings, QUser root) {
        bindings.bind(String.class).first(
          (StringPath path, String value) -> path.containsIgnoreCase(value));
        bindings.excluding(root.email);
    }
}

ご了承ください:

  • デフォルトのバインディングをカスタマイズするために、QuerydslBinderCustomizercustomize()をオーバーライドしています

  • すべてのStringプロパティの大文字と小文字を無視するように、デフォルトのequalsバインディングをカスタマイズしています

  • また、Predicateの解像度からユーザーのメールを除外しています

完全なドキュメントhereを確認してください。

4. ユーザーコントローラー

それでは、コントローラーを見てみましょう。

@RequestMapping(method = RequestMethod.GET, value = "/users")
@ResponseBody
public Iterable findAllByWebQuerydsl(
  @QuerydslPredicate(root = User.class) Predicate predicate) {
    return userRepository.findAll(predicate);
}

これは興味深い部分です。@QuerydslPredicateアノテーションを使用してwe’re obtaining a Predicate directly out of the HttpRequestがどのようになっているかに注目してください。

このタイプのクエリを含むURLは次のようになります。

http://localhost:8080/users?firstName=john

そして、潜在的な応答がどのように構造化されるかを次に示します。

[
   {
      "id":1,
      "firstName":"john",
      "lastName":"doe",
      "email":"[email protected]",
      "age":11
   }
]

5. ライブテスト

最後に、新しいQuerydslWebサポートをテストしてみましょう。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class UserLiveTest {

    private ObjectMapper mapper = new ObjectMapper();
    private User userJohn = new User("john", "doe", "[email protected]");
    private User userTom = new User("tom", "doe", "[email protected]");

    private static boolean setupDataCreated = false;

    @Before
    public void setupData() throws JsonProcessingException {
        if (!setupDataCreated) {
            givenAuth().contentType(MediaType.APPLICATION_JSON_VALUE)
                       .body(mapper.writeValueAsString(userJohn))
                       .post("http://localhost:8080/users");

            givenAuth().contentType(MediaType.APPLICATION_JSON_VALUE)
                       .body(mapper.writeValueAsString(userTom))
                       .post("http://localhost:8080/users");
            setupDataCreated = true;
        }
    }

    private RequestSpecification givenAuth() {
        return RestAssured.given().auth().preemptive().basic("user1", "user1Pass");
    }
}

まず、システム内のすべてのユーザーを取得しましょう。

@Test
public void whenGettingListOfUsers_thenCorrect() {
    Response response = givenAuth().get("http://localhost:8080/users");
    User[] result = response.as(User[].class);
    assertEquals(result.length, 2);
}

次に、first nameでユーザーを見つけましょう。

@Test
public void givenFirstName_whenGettingListOfUsers_thenCorrect() {
    Response response = givenAuth().get("http://localhost:8080/users?firstName=john");
    User[] result = response.as(User[].class);
    assertEquals(result.length, 1);
    assertEquals(result[0].getEmail(), userJohn.getEmail());
}

次に、partial last nameでユーザーを見つけないようにします。

@Test
public void givenPartialLastName_whenGettingListOfUsers_thenCorrect() {
    Response response = givenAuth().get("http://localhost:8080/users?lastName=do");
    User[] result = response.as(User[].class);
    assertEquals(result.length, 2);
}

それでは、emailでユーザーを見つけてみましょう。

@Test
public void givenEmail_whenGettingListOfUsers_thenIgnored() {
    Response response = givenAuth().get("http://localhost:8080/users?email=john");
    User[] result = response.as(User[].class);
    assertEquals(result.length, 2);
}

注:メールでユーザーを検索しようとすると、ユーザーのメールをPredicateの解像度から除外したため、クエリは無視されました。

6. 結論

この記事では、Spring Data Querydsl Webサポートの概要と、HTTPリクエストから直接Predicateを取得し、それを使用してデータを取得するためのクールでシンプルな方法について説明しました。