1. 概述
在本教程中,我们将使用 Spring Data JPA 和 Specifications 构建一个 搜索/过滤 REST API。
我们之前在 本系列第一篇文章 中探讨过基于 JPA Criteria 的查询语言实现。那么,为什么需要查询语言?
因为对于复杂的 API 来说,仅通过简单的字段进行搜索/过滤是远远不够的。查询语言更加灵活,可以让我们精确地过滤出所需的资源。
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;
// 标准 getter 和 setter
}
3. 使用 Specification 实现过滤
接下来是核心部分:使用 Spring Data JPA 的 Specifications 实现查询逻辑。
我们创建一个 UserSpecification 类并实现 Specification 接口,通过传入自定义的约束条件来构造查询:
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;
}
}
上述实现中,我们基于一个 SearchCriteria 类来表示查询条件:
public class SearchCriteria {
private String key;
private String operation;
private Object value;
}
该类包含以下字段:
key
:字段名,例如firstName
、age
等operation
:操作符,如=
、<
、>
等value
:字段值,例如john
、25
等
虽然当前实现较为简单,但已经能作为构建强大查询逻辑的基础。
4. UserRepository
接下来定义 UserRepository,通过继承 JpaSpecificationExecutor 来获得 Specification 的相关方法:
public interface UserRepository
extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {}
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@example.com");
userJohn.setAge(22);
repository.save(userJohn);
userTom = new User();
userTom.setFirstName("Tom");
userTom.setLastName("Doe");
userTom.setEmail("tom.doe@example.com");
userTom.setAge(26);
repository.save(userTom);
}
}
✅ 根据姓氏搜索用户
@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));
}
✅ 同时根据姓名和姓氏搜索
@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)));
}
✅ 根据姓氏和最小年龄搜索
@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)));
}
✅ 根据部分姓名搜索
@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. 组合 Specifications
为了支持更复杂的查询条件,我们构建一个 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
最后,我们创建一个 UserController 来暴露 REST 接口:
@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);
}
}
✅ 示例请求
http://localhost:8082/spring-rest-query-language/auth/users?search=lastName:doe,age>25
✅ 示例响应
[{
"id":2,
"firstName":"tom",
"lastName":"doe",
"email":"tom.doe@example.com",
"age":26
}]
⚠️ 注意:由于当前使用逗号 ,
分隔查询条件,因此查询值中不能包含该字符。如需支持逗号,可使用 ;
替代,或通过引号包裹字段值。
8. 总结
本文演示了如何使用 Spring Data JPA 的 Specifications 构建灵活的 REST 查询语言。通过封装查询逻辑,我们实现了:
✅ 多条件组合查询
✅ 支持模糊匹配、范围查询
✅ 清晰的接口设计与可扩展性
完整的项目代码可在 GitHub 仓库 中找到。该项目基于 Maven 构建,可直接导入运行。
如果你希望为你的 API 提供更强大的查询能力,这个方案是一个简单而实用的起点。