gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:32:22 42 4
gpt4 key购买 nike

我正在使用 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/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com