知識庫 / Spring RSS 訂閱

REST 查詢語言與 Querydsl Web 支持

Persistence,REST,Spring
HongKong
4
03:59 AM · Dec 06 ,2025
<div>
 <a class="article-series-header" href="javascript:void(0);">該文章是系列的一部分</a>
 <div>
  <div>
   • 使用 Spring 和 JPA Criteria 的 REST 查詢語言
   <br>
   • 使用 Spring Data JPA Specifications 的 REST 查詢語言
   <br>
   • 使用 Spring Data JPA 和 Querydsl 的 REST 查詢語言
   <br>
   • REST 查詢語言 – 高級搜索操作
   <br>
   • REST 查詢語言 – 實現 OR 操作
   <br>
   • 使用 RSQL 的 REST 查詢語言
   <br>
   <div>
    • 使用 Querydsl Web 支持的 REST 查詢語言 (當前文章)
   </div>
  </div>
  </div>
  </div>
  </div>

1. 概述

在本快速教程中,我們將討論 Spring Data Querydsl Web 支持。

這絕對是相對於我們之前在 REST Query Language 主系列中關注的所有方法的有趣替代方案。

2. Maven 配置

首先,讓我們來查看我們的 Maven 配置:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>${querydsl.version}</version>
    </dependency>
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-jpa</artifactId>
        <version>${querydsl.version}</version>
    </dependency>
...

請注意,Querydsl 的 Web 支持自 spring-data-commons 1.11 版本起可用。

3. 用户存儲庫

接下來,讓我們來查看我們的存儲庫:

public interface UserRepository extends 
  JpaRepository<User, Long>, QueryDslPredicateExecutor<User>, QuerydslBinderCustomizer<QUser> {
    @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() 方法,以自定義默認綁定
  • 我們正在自定義默認的 equals 綁定,忽略所有 String 屬性的大小寫
  • 我們還排除了用户電子郵件從 Predicate 解析中

請查看完整文檔 在此處

4. 用户控制器

現在,讓我們來查看一下控制器:

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

這是關鍵部分——請注意,我們直接從 HttpRequest 中獲取 Predicate,使用 @QuerydslPredicate 註解。

下面是一個使用這種查詢類型的 URL 的示例:

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

下面展示了潛在響應的結構方式:

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

5. 實時測試

最後,讓我們測試一下新的 Querydsl Web 支持:

@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);
}

接下來,我們按名查找用户:

@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());
}

接下來,我們按部分姓氏查找用户:

@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);
}

現在,讓我們嘗試通過 郵箱 查找用户:

@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,並利用它來檢索數據。

« 之前
REST 查詢語言與 RSQL
user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.