The definition of EntityGraph in the JPA Spring data repository is static. If you want it to be dynamic, you need to do it programmatically, like on 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);
You can also define a method with 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); }
And then you have a method in your service that uses this method with EntityGraph or inline findOne(T id) without EntityGraph:
Product findOneById(Long id, boolean withTags){ if(withTags){ return productRepository.findOneByIdWithEntityGraphTags(id); } else { return productRepository.findOne(id); } }
source share