java - 需要最佳的实体和查询设计来获取具有多个关联的对象

标签 java hibernate spring-boot

我有一个实体,它有多个 @ManyToOne 关联对象。目前,我将所有关联的对象获取类型建模为 LAZY。

实际上我正在编写REST API来支持各种功能,例如

  1. 获取带有 @ManytoOne 注释的实体,仅解析为 ID
  2. 获取带有解析整个对象的 @ManytoOne 注释的实体
  3. 获取带有解析为部分对象的 @ManytoOne 注释的实体
  4. 使用 @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: The ExampleMatcher carries details on how to match particular fields. It can be reused across multiple Examples.
  • Example: An Example consists of the probe and the ExampleMatcher. 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/

相关文章:

java - 从十六进制颜色转换为 RGB

java - 图形不会覆盖整个 Canvas

java - JPA @OneToOne 在映射到具有子类的抽象@Entity 时抛出错误

hibernate - Grails命名查询NOT IN

java - Spring security oauth2 - 在 oauth/token 调用后添加过滤器

java - 以编程方式显示操作栏溢出

java - 如何从 RESTFul Web 服务访问本地文件

database - Hibernate Criteria 一对多关系

java - 是否可以在 Spring Boot 中将 MongoDb 和 PostgreSql 用于同一模型?

java - SpringFox,带有 JpaRepository 的 Spring Data Rest - Swagger 无法识别带有 spring boot 的 Rest 存储库