2015-11-27 10 views
5

JPAを使用してSpringブートを使用してアプリケーションを開発しています。 アプリケーションでは、私は休息APIを公開しています。私は、データを完全に制御したいので、Springのデータ・レストを使用したくありません。SpringブートでEntityGraphを動的に取得する方法

EntityGraphを動的に使用する方法を理解できません。

私がアクセス製品に http://localhost:8090/product/1

を、残りのリンクを以下している私はhere

@Entity 
class Product { 

    @ManyToMany 
    Set<Tag> tags; 

    // other properties omitted 
} 

interface ProductRepository extends Repository<Customer, Long> { 

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

から取られたモデルを、次のしていると仮定それはidを持つ私に1つの

質問積を返します:

  1. デフールで私は@EntityGraphについて述べたので、タグを取得しますか? はいの場合、オンデマンドで設定できますか?もしクエリ内にあれば 文字列があります。include =タグの場合、そのタグを で取得したいだけです。

私はthisの記事を見つけましたが、これがどのように役立つかはわかりません。

答えて

6

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でメソッドを定義することができます。

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

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)を内蔵したこのメソッドを使用して、あなたのサービスのメソッドを持っています

関連する問題