java - 如何在 Spring Boot 中动态获取 EntityGraph

标签 java spring jpa spring-data spring-data-jpa

我正在使用 JPA 使用 Spring Boot 开发应用程序。 在应用程序中,我公开了一个休息 API。我不想使用 Spring data rest,因为我想完全控制数据。

我不知道如何动态使用 EntityGraph。

假设我有以下来自 here 的模型

   @Entity
class Product {

  @ManyToMany
  Set<Tag> tags;

  // other properties omitted
}

interface ProductRepository extends Repository<Customer, Long> {

  @EntityGraph(attributePaths = {"tags"})
  Product findOneById(Long id);
}

我有以下访问产品的其余链接 http://localhost:8090/product/1

它返回给我一个 id 为 1 的产品

问题:

  1. 它会像我们提到的@EntityGraph 那样默认获取标签吗? 如果是,那么可以按需配置吗?说,如果在查询中 string 我有 include=tags,那么我只想获取产品 它的标签。

我找到了 this文章,但不确定这有什么帮助。

最佳答案

Spring Data JPA Repository 中EntityGraph 的定义是静态的。如果你想让它动态化,你需要像在你链接到的页面中一样以编程方式执行此操作:

EntityGraph<Product> graph = this.em.createEntityGraph(Product.class);
graph.addAttributeNodes("tags"); //here you can add or not the tags

Map<String, Object> hints = new HashMap<String, Object>();
hints.put("javax.persistence.loadgraph", graph);

this.em.find(Product.class, orderId, hints);

您还可以使用 JPA 存储库中的 EntityGraph 定义方法。

interface ProductRepository extends Repository<Product, Long> {

@EntityGraph(attributePaths = {"tags"})
@Query("SELECT p FROM Product p WHERE p.id=:id")
Product findOneByIdWithEntityGraphTags(@Param("id") Long id);
}

然后在您的服务中有一个方法,该方法将此方法与 EntityGraph 或不带 EntityGraph 的内置 findOne(T id) 一起使用:

Product findOneById(Long id, boolean withTags){
  if(withTags){
    return productRepository.findOneByIdWithEntityGraphTags(id);
  } else {
    return productRepository.findOne(id);
  }
}

关于java - 如何在 Spring Boot 中动态获取 EntityGraph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33957291/

相关文章:

java - While 循环仅在一次迭代中终止

java - yml配置中的spring boot spring EL

java - HTML 表单提交不适用于 Spring Boot 2.3.1

java - 发送 JMS 消息的单元测试代码

mysql - 带连接的 spring data jpa native 查询

java - NoClassDefFoundError 无法初始化类

java - 无法将 jar 从 MavenLocal 导入 Android Studio - 意外的顶级异常 : finished with non-zero exit value 1

java - 谁能帮我写一个更新查询

java - Tomcat 8 + MySQL + Spring + JPA - 无法为连接 URL '' 创建类 'null' 的 JDBC 驱动程序

java - 实现 oneToMany 关系的最佳实践是什么?