案例概述
在本系列的第一篇文章中,咱們將探索一種用於REST API的簡單查詢語言。咱們將充分利用Spring做爲REST API,並將JPA 2標準用於持久性方面。html
爲何使用查詢語言?由於 - 對於任何複雜的API - 經過很是簡單的字段搜索/過濾資源是不夠的。查詢語言更靈活,容許您精確過濾所需的資源。java
User Entity
首先 - 讓咱們提出咱們將用於過濾器/搜索API的簡單實體 - 一個基本用戶:spring
@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進行過濾
如今 - 讓咱們深刻研究問題 - 持久層中的查詢。數據庫
構建查詢抽象是一個平衡問題。一方面咱們須要很大的靈活性,另外一方面咱們須要保持複雜性可管理性。高級別,功能很簡單 - 你傳遞一些約束,你會獲得一些結果。json
讓咱們看看它是如何工做的:api
@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獲取很是簡單的約束列表,根據這些約束組成查詢,執行搜索並返回結果。bash
約束類也很簡單:app
public class SearchCriteria { private String key; private String operation; private Object value; }
該SearchCriteria實現持有咱們的查詢參數:less
測試搜索查詢
如今 - 讓咱們測試咱們的搜索機制,以確保它可用。ide
首先 - 讓咱們經過添加兩個用戶來初始化咱們的數據庫以進行測試 - 以下例所示:
@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上實現這種過濾功能的堅實起點。