Spring Data JPA REST Query Criteria

案例概述html

本系列的第一篇文章中,咱們將探索一種用於REST API的簡單查詢語言。咱們將充分利用Spring做爲REST API,並將JPA 2標準用於持久性方面。java

**爲何使用查詢語言?**由於 - 對於任何複雜的API - 經過很是簡單的字段搜索/過濾資源是不夠的。查詢語言更靈活,容許您精確過濾所需的資源。spring

User Entity數據庫

首先 - 讓咱們提出咱們將用於過濾器/搜索API的簡單實體 - 一個基本用戶:json

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
 
    private String firstName;
    private String lastName;
    private String email;
 
    private int age;
}
複製代碼

使用CriteriaBuilder進行過濾api

如今 - 讓咱們深刻研究問題 - 持久層中的查詢。bash

構建查詢抽象是一個平衡問題。一方面咱們須要很大的靈活性,另外一方面咱們須要保持複雜性可管理性。高級別,功能很簡單 - 你傳遞一些約束,你會獲得一些結果app

讓咱們看看它是如何工做的:less

@Repository
public class UserDAO implements IUserDAO {
 
    @PersistenceContext
    private EntityManager entityManager;
 
    @Override
    public List<User> searchUser(List<SearchCriteria> params) {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<User> query = builder.createQuery(User.class);
        Root r = query.from(User.class);
 
        Predicate predicate = builder.conjunction();
 
        for (SearchCriteria param : params) {
            if (param.getOperation().equalsIgnoreCase(">")) {
                predicate = builder.and(predicate, 
                  builder.greaterThanOrEqualTo(r.get(param.getKey()), 
                  param.getValue().toString()));
            } else if (param.getOperation().equalsIgnoreCase("<")) {
                predicate = builder.and(predicate, 
                  builder.lessThanOrEqualTo(r.get(param.getKey()), 
                  param.getValue().toString()));
            } else if (param.getOperation().equalsIgnoreCase(":")) {
                if (r.get(param.getKey()).getJavaType() == String.class) {
                    predicate = builder.and(predicate, 
                      builder.like(r.get(param.getKey()), 
                      "%" + param.getValue() + "%"));
                } else {
                    predicate = builder.and(predicate, 
                      builder.equal(r.get(param.getKey()), param.getValue()));
                }
            }
        }
        query.where(predicate);
 
        List<User> result = entityManager.createQuery(query).getResultList();
        return result;
    }
 
    @Override
    public void save(User entity) {
        entityManager.persist(entity);
    }
}
複製代碼

如您所見,searchUser API獲取很是簡單的約束列表,根據這些約束組成查詢,執行搜索並返回結果。ide

約束類也很簡單:

public class SearchCriteria {
    private String key;
    private String operation;
    private Object value;
}
複製代碼

該SearchCriteria實現持有咱們的查詢參數:

  • key:用於保存字段名稱 - 例如:firstName,age,...等。
  • operation:用於保持操做 - 例如:Equality,less,...等。
  • value:用於保存字段值 - 例如:john,25,...等。

測試搜索查詢

如今 - 讓咱們測試咱們的搜索機制,以確保它可用。

首先 - 讓咱們經過添加兩個用戶來初始化咱們的數據庫以進行測試 - 以下例所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class })
@Transactional
@TransactionConfiguration
public class JPACriteriaQueryTest {
 
    @Autowired
    private IUserDAO userApi;
 
    private User userJohn;
 
    private User userTom;
 
    @Before
    public void init() {
        userJohn = new User();
        userJohn.setFirstName("John");
        userJohn.setLastName("Doe");
        userJohn.setEmail("john@doe.com");
        userJohn.setAge(22);
        userApi.save(userJohn);
 
        userTom = new User();
        userTom.setFirstName("Tom");
        userTom.setLastName("Doe");
        userTom.setEmail("tom@doe.com");
        userTom.setAge(26);
        userApi.save(userTom);
    }
}
複製代碼

如今,讓咱們獲得一個具備特定firstName和lastName的用戶 - 以下例所示:

@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
    List<SearchCriteria> params = new ArrayList<SearchCriteria>();
    params.add(new SearchCriteria("firstName", ":", "John"));
    params.add(new SearchCriteria("lastName", ":", "Doe"));
 
    List<User> results = userApi.searchUser(params);
 
    assertThat(userJohn, isIn(results));
    assertThat(userTom, not(isIn(results)));
}
複製代碼

接下來,讓咱們獲得一個具備相同lastName的用戶列表:

@Test
public void givenLast_whenGettingListOfUsers_thenCorrect() {
    List<SearchCriteria> params = new ArrayList<SearchCriteria>();
    params.add(new SearchCriteria("lastName", ":", "Doe"));
 
    List<User> results = userApi.searchUser(params);
    assertThat(userJohn, isIn(results));
    assertThat(userTom, isIn(results));
}
複製代碼

接下來,讓age大於或等於25的用戶:

@Test
public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() {
    List<SearchCriteria> params = new ArrayList<SearchCriteria>();
    params.add(new SearchCriteria("lastName", ":", "Doe"));
    params.add(new SearchCriteria("age", ">", "25"));
 
    List<User> results = userApi.searchUser(params);
 
    assertThat(userTom, isIn(results));
    assertThat(userJohn, not(isIn(results)));
}
複製代碼

接下來,讓咱們搜索實際不存在的用戶:

@Test
public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() {
    List<SearchCriteria> params = new ArrayList<SearchCriteria>();
    params.add(new SearchCriteria("firstName", ":", "Adam"));
    params.add(new SearchCriteria("lastName", ":", "Fox"));
 
    List<User> results = userApi.searchUser(params);
    assertThat(userJohn, not(isIn(results)));
    assertThat(userTom, not(isIn(results)));
}
複製代碼

最後,讓咱們搜索僅給出部分firstName的用戶:

@Test
public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() {
    List<SearchCriteria> params = new ArrayList<SearchCriteria>();
    params.add(new SearchCriteria("firstName", ":", "jo"));
 
    List<User> results = userApi.searchUser(params);
 
    assertThat(userJohn, isIn(results));
    assertThat(userTom, not(isIn(results)));
}
複製代碼

UserController

最後,讓咱們如今將這種靈活搜索的持久性支持鏈接到咱們的REST API。

咱們將設置一個簡單的UserController - 使用findAll()使用「search」傳遞整個搜索/過濾器表達式

@Controller
public class UserController {
 
    @Autowired
    private IUserDao api;
 
    @RequestMapping(method = RequestMethod.GET, value = "/users")
    @ResponseBody
    public List<User> findAll(@RequestParam(value = "search", required = false) String search) {
        List<SearchCriteria> params = new ArrayList<SearchCriteria>();
        if (search != null) {
            Pattern pattern = Pattern.compile("(\w+?)(:|<|>)(\w+?),");
            Matcher matcher = pattern.matcher(search + ",");
            while (matcher.find()) {
                params.add(new SearchCriteria(matcher.group(1), 
                  matcher.group(2), matcher.group(3)));
            }
        }
        return api.searchUser(params);
    }
}
複製代碼

請注意咱們如何簡單地從搜索表達式中建立搜索條件對象。

咱們如今正處於開始使用API​​並確保一切正常工做的地步:

http://localhost:8080/users?search=lastName:doe,age>25
複製代碼

這是它的迴應:

[{
    "id":2,
    "firstName":"tom",
    "lastName":"doe",
    "email":"tom@doe.com",
    "age":26
}]
複製代碼

案例結論

這個簡單而強大的實現支持對REST API進行至關多的智能過濾。是的—它仍然很粗糙,能夠改進(下一篇文章將對此進行改進)—但它是在api上實現這種過濾功能的堅實起點。

相關文章
相關標籤/搜索