我正在使用JPA使用Spring Boot开发应用程序。在应用程序中,我将公开一个REST API。我不想使用Spring数据休息,因为我想完全控制数据。
我无法弄清楚如何动态使用EntityGraph。
假设我有以下模型取自这里
@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的产品
问题:
我找到了这篇文章,但不确定如何提供帮助。
Spring Data JPA存储库中的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一起使用,或者在findOne(T id)
没有EntityGraph的情况下使用此方法:
Product findOneById(Long id, boolean withTags){
if(withTags){
return productRepository.findOneByIdWithEntityGraphTags(id);
} else {
return productRepository.findOne(id);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句