2015-11-27 15 views
5

Sto sviluppando un'applicazione utilizzando Spring Boot utilizzando JPA. Nell'applicazione sto esponendo l'API resto. Non voglio usare il resto dei dati di Spring perché voglio avere il pieno controllo dei dati.Come scaricare EntityGraph dinamicamente in Spring Boot

Non riesco a capire come utilizzare EntityGraph in modo dinamico.

Supponiamo che io abbia seguente modello preso da here

@Entity 
class Product { 

    @ManyToMany 
    Set<Tag> tags; 

    // other properties omitted 
} 

interface ProductRepository extends Repository<Customer, Long> { 

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

Ho seguente link riposo per accedere prodotto http://localhost:8090/product/1

Mi ritorna prodotto con id 1

Domande:

  1. Lo farà di default t recuperare i tag come abbiamo menzionato @EntityGraph? Se sì, allora può essere configurato su richiesta? Di ', se nella stringa ho include = tag, quindi voglio solo recuperare il prodotto con i suoi tag.

Ho trovato l'articolo this ma non so come possa essere d'aiuto.

risposta

6

La definizione di EntityGraph nel repository JPA Data Spring è statica. Se si vuole avere dinamica è necessario fare questo programatically come nella pagina si è collegato a:

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); 

Inoltre è possibile definire il metodo con l'EntityGraph nel vostro 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); 
} 

e poi avere un metodo nel vostro servizio che utilizza questo metodo con l'EntityGraph o il costruito nel findOne(T id) senza l'EntityGraph:

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