如何在Spring Boot中动态获取EntityGraph [英] How to fetch EntityGraph dynamically in Spring Boot

查看:62
本文介绍了如何在Spring Boot中动态获取EntityGraph的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JPA使用Spring Boot开发应用程序.在应用程序中,我将公开一个REST API.我不想使用Spring数据其余部分我想有数据的完全控制.

I am developing an application using Spring Boot using JPA. In the application I am exposing a rest API. I do not want to use Spring data rest as I want to have full control of the data.

我无法弄清楚如何动态使用EntityGraph.

I am not able to figure out how to use EntityGraph dynamically.

假设我从此处

   @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

I have following rest link to access Product http://localhost:8090/product/1

它向我返回ID为1的产品

It returns to me a product with id 1

问题:

  1. 默认情况下是否会像我们提到的@EntityGraph那样获取标签?如果是,那么可以按需配置吗?说,如果在查询中字符串,我有 include = tags ,那么只有我想用它的标签.
  1. Will it by default fetch tags as we have mentioned @EntityGraph? If yes, then can this be configured on demand? Say, if in the query string I have include=tags, then only I want to fetch product with its tags.

我发现了文章,但不确定如何提供帮助.

I found this article but not sure how this can be of help.

推荐答案

Spring Data JPA存储库中EntityGraph的定义是静态的.如果要使其动态化,则需要像链接到的页面那样以编程方式进行此操作:

The definition of the EntityGraph in the Spring Data JPA Repository is static. If you want to have it dynamic you need to do this programatically like in the page you linked to:

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定义方法.

Also you can define the method with the EntityGraph in your JPA Repository.

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或内置的 findOne(T id)一起使用,而没有EntityGraph:

And then have a method in your service which uses this method with the EntityGraph or the built in findOne(T id) without the EntityGraph:

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

这篇关于如何在Spring Boot中动态获取EntityGraph的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆