java - Spring Boot 中的标准 API
问题描述
我有以下(简化的)实体结构:
public class Animal {
private long id;
private int regionId;
private int categoryId;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "animal")
private List<Attributes> attributes;
}
public class Attributes {
private long id;
@ManyToOne(fetch = FetchType.LAZY)
private Animal animal;
private String name;
private String value;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Detail detail;
}
public class Detail {
private long id;
private String size;
private String type;
}
这是 Spring Boot 应用程序的一部分。
我想要实现的是通过Animal自己的属性和Details中的属性来查询。
我的查询需要如下所示:
GET: /animal/{regionId}/{categoryId}?size=medium,large&type=carnivorous,herbivore
这意味着我需要请求所有具有特定 regionId 和 categoryId 并且在提供的值列表中具有大小和类型的详细信息的动物。另外 - 我认为这是棘手的部分 -大小和类型参数是可选的,因此查询需要考虑到这一点。
目前我有一个扩展 CrudRepository 并为Plan实体提供基本查询方法的 PlanRepository。
我试图围绕 Criteria API 寻找一种方法来使用它来实现这一目标,但我不明白如何将所有这些都放在我的存储库中。有任何想法吗?
解决方案
你应该看看 Spring Data JPA Specifications:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications
您必须从 JpaSpecificationExecutor 扩展您的存储库
public interface CustomerRepository
extends CrudRepository<Customer, Long>, JpaSpecificationExecutor {
…
}
然后是一个采用 Specification 参数的 findAll 方法:
List<T> findAll(Specification<T> spec);
然后,您可以根据 URL 中传递的参数创建规范:
public static Specification<Animal> bySizeAndType(String size, String type) {
return new Specification<Animal>() {
public Predicate toPredicate(Root<Animal> root, CriteriaQuery<?> query,
CriteriaBuilder builder) {
// JOIN Attributes
// JOIN Detail
if (size != null) {
// add condition
}
if (type != null) {
// add condition
}
return builder.where(...);
}
};
}
我希望这有帮助。
推荐阅读
- scala - 处理隐式类型类冲突
- python - Python:根据另一列名称获取一列的值
- node.js - 无法使用 node-dev 监视目录
- mongodb - MongoDB 数据模型 - 一个文档可以链接到具有不同状态的多个文档
- python - 使用 pandas 模式的 Python 库列验证
- sql-server - 如何将多列值转换为 SQL 中一组值的标题?
- ajax - Wordpress - 当搜索字符串输入 AJAX 搜索字段时触发脚本?
- javascript - 任何可以按对象值填充区域的图表库
- excel - Excel 如何使用 `Ymd H:i:s` 验证
- c# - 你如何使用实例化连续生成对象?