1、概览 {#1概览}
上一篇文章 介绍了一个基于 JPA Criteria 的查询语言解决方案。
本文将带你了解如何使用 Spring Data JPA 和 Specification
构建一个搜索/过滤 REST API。
2、 User 实体 {#2-user-实体}
创建一个 User
实体类,用于检索 API:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private int age;
// get、set 方法
}
3、使用 Specification 进行过滤 {#3使用-specification-进行过滤}
来看看如何使用自定义 Spring Data JPA Specification 进行查询。
创建一个实现 Specification
接口的 UserSpecification
,并传入自己的约束条件来构建实际查询:
public class UserSpecification implements Specification<User> {
private SearchCriteria criteria;
@Override
public Predicate toPredicate
(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (criteria.getOperation().equalsIgnoreCase(">")) {
return builder.greaterThanOrEqualTo(
root.<String> get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase("<")) {
return builder.lessThanOrEqualTo(
root.<String> get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase(":")) {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(
root.<String>get(criteria.getKey()), "%" + criteria.getValue() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
return null;
}
}
如上,我们根据一些简单的约束条件创建了一个 Specification
,包含这些约束条件的 SearchCriteria
类如下:
public class SearchCriteria {
private String key;
private String operation;
private Object value;
}
SearchCriteria
实现包含一个约束条件的基本表示,我们会根据这个约束条件来构建查询:
key
:字段名,如name
、age
等。operation
:操作,例如等于、小于等。value
:字段值,如john
、25
等。
当然,这种实现方式比较简单,还可以改进。不过,它为我们所需的强大而灵活的操作奠定了坚实的基础。
4、UserRepository {#4userrepository}
接着,来看看 UserRepository
。
只需继承 JpaSpecificationExecutor
即可获得 Specification
API:
public interface UserRepository
extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {}
5、测试搜索过滤 {#5测试搜索过滤}
首先,创建几个用户,用于测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class })
@Transactional
@TransactionConfiguration
public class JPASpecificationIntegrationTest {
@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("john@doe.com");
userJohn.setAge(22);
repository.save(userJohn);
userTom = new User();
userTom.setFirstName("Tom");
userTom.setLastName("Doe");
userTom.setEmail("tom@doe.com");
userTom.setAge(26);
repository.save(userTom);
}
}
根据 lastName
检索用户:
@Test
public void givenLast_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List<User> results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, isIn(results));
}
根据 firstName
和 lastName
检索用户:
@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("firstName", ":", "john"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List<User> results = repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
注意 :这里使用 where
和 and
来合并 Specification
。
检索 lastName
等于 doe
并且 age
大于 25
的用户:
@Test
public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("age", ">", "25"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
List<User> results =
repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userTom, isIn(results));
assertThat(userJohn, not(isIn(results)));
}
检索不存在的用户:
@Test
public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec1 =
new UserSpecification(new SearchCriteria("firstName", ":", "Adam"));
UserSpecification spec2 =
new UserSpecification(new SearchCriteria("lastName", ":", "Fox"));
List<User> results =
repository.findAll(Specification.where(spec1).and(spec2));
assertThat(userJohn, not(isIn(results)));
assertThat(userTom, not(isIn(results)));
}
根据 firstName
模糊检索:
@Test
public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() {
UserSpecification spec =
new UserSpecification(new SearchCriteria("firstName", ":", "jo"));
List<User> results = repository.findAll(spec);
assertThat(userJohn, isIn(results));
assertThat(userTom, not(isIn(results)));
}
6、组合 Specification {#6组合-specification}
实现一个 UserSpecificationsBuilder
来把自定义的 Specification
组起来,以使用多个约束条件并根据多个条件进行过滤。
SpecSearchCriteria
如下:
public class SpecSearchCriteria {
private String key;
private SearchOperation operation;
private Object value;
private boolean orPredicate;
public boolean isOrPredicate() {
return orPredicate;
}
}
UserSpecificationsBuilder
如下:
public class UserSpecificationsBuilder {
private final List<SpecSearchCriteria> params;
public UserSpecificationsBuilder() {
params = new ArrayList<>();
}
public final UserSpecificationsBuilder with(String key, String operation, Object value,
String prefix, String suffix) {
return with(null, key, operation, value, prefix, suffix);
}
public final UserSpecificationsBuilder with(String orPredicate, String key, String operation,
Object value, String prefix, String suffix) {
SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0));
if (op != null) {
if (op == SearchOperation.EQUALITY) { // 该操作可能是复杂的操作
boolean startWithAsterisk = prefix != null &&
prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX);
boolean endWithAsterisk = suffix != null &&
suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX);
if (startWithAsterisk && endWithAsterisk) {
op = SearchOperation.CONTAINS;
} else if (startWithAsterisk) {
op = SearchOperation.ENDS_WITH;
} else if (endWithAsterisk) {
op = SearchOperation.STARTS_WITH;
}
}
params.add(new SpecSearchCriteria(orPredicate, key, op, value));
}
return this;
}
public Specification build() {
if (params.size() == 0)
return null;
Specification result = new UserSpecification(params.get(0));
for (int i = 1; i < params.size(); i++) {
result = params.get(i).isOrPredicate()
? Specification.where(result).or(new UserSpecification(params.get(i)))
: Specification.where(result).and(new UserSpecification(params.get(i)));
}
return result;
}
}
7、UserController {#7usercontroller}
最后,创建一个 REST API 来使用搜索/过滤功能:
@Controller
public class UserController {
@Autowired
private UserRepository repo;
@RequestMapping(method = RequestMethod.GET, value = "/users")
@ResponseBody
public List<User> 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<User> spec = builder.build();
return repo.findAll(spec);
}
}
注意,可以更改 Pattern
对象来支持其他非英语系统。
Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),", Pattern.UNICODE_CHARACTER_CLASS);
测试 API:
http://localhost:8080/users?search=lastName:doe,age>25
响应如下:
[{
"id":2,
"firstName":"tom",
"lastName":"doe",
"email":"tom@doe.com",
"age":26
}]
在 Pattern
中,搜索由逗号 "," 分割,因此搜索条件不能包含该字符。该 Pattern
也不匹配空白。
如果要搜索包含逗号,可以考虑使用不同的分隔符,如 ";"。
另一种方法是更改 Pattern
,搜索引号之间的值,然后从搜索条件中去除这些引号:
Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\"([^\"]+)\")");
8、总结 {#8总结}
本文介绍了如何使用 Spring Data Specification 来构建 REST 查询语言,还介绍了如何在 Rest API 中使用该语言进行数据过滤。
Ref:https://www.baeldung.com/rest-api-search-language-spring-data-specifications