我有一个实体,它有多个 @ManyToOne
关联对象。目前,我将所有关联的对象获取类型建模为 LAZY。
实际上我正在编写REST API
来支持各种功能,例如
- 获取带有
@ManytoOne
注释的实体,仅解析为 ID - 获取带有解析整个对象的
@ManytoOne
注释的实体 - 获取带有解析为部分对象的
@ManytoOne
注释的实体 - 使用
@ManytoOne
注释获取仅解析为 ID 的实体
我的应用程序是使用 spring-boot jpa 存储库构建的。显然,REST API
中的上述变化可以通过为每个 API
编写命名查询来解决。如果我这样做,在某一时刻,每个关联对象都会有多个命名查询。但我期待有更好的方法来建模和查询实体。
如有任何建议,我们将不胜感激。
最佳答案
根据我的理解,你应该使用 Query by Example
The Query by Example API consists of three parts:
- Probe: The actual example of a domain object with populated fields.
ExampleMatcher
: TheExampleMatcher
carries details on how to match particular fields. It can be reused across multipleExamples
.Example
: AnExample
consists of the probe and theExampleMatcher
. It is used to create the query.Query by Example is well suited for several use cases:
- Querying your data store with a set of static or dynamic constraints.
- Frequent refactoring of the domain objects without worrying about breaking existing queries.
- Working independently from the underlying data store API.
Query by Example also has several limitations:
- No support for nested or grouped property constraints, such as
firstname = ?0 or (firstname = ?1 and lastname = ?2)
.- Only supports starts/contains/ends/regex matching for strings and exact matching for other property types.
关于java - 需要最佳的实体和查询设计来获取具有多个关联的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51099751/