2016-12-03 48 views
1

我使用和jpa,我試圖從jparepository從父實體和子實體獲取數據。jpa存儲庫findAll與父母和孩子使用可配頁

父實體:

@Entity 
@Table(name = "parent") 
public class Parent { 
    @Id 
    private int id; 

    private String name; 

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) 
    private Set<Child> children; 
} 

子實體:

@Entity 
@Table(name = "child") 
public class Child { 

    @Id 
    private int id; 

    private String name; 

    private int parent_id; 

    @ManyToOne 
    @JoinColumn(name = "parent_id", referencedColumnName = "id") 
    private Parent parent; 

jpaRepository:

public interface ParentRepository extends JpaRepository<Parent, Integer>, JpaSpecificationExecutor<Parent> { 

} 

我的fecth設置爲FetchType.LAZY的原因是,有時我只是想獲得父母沒有孩子。

所以,這裏是我的問題: 當我使用

parentRepository.findAll(pagable); 

結果只包含父母,沒有孩子,但我想要的結果包含的孩子,而且在某些情況下,我不希望它。如何寫它?

+0

你可以用@Transactinal註解做到這一點。 有關更多詳細信息,請參閱此答案http://stackoverflow.com/questions/26611173/jpa-jta-transactional-spring-annotation/26615390#26615390 –

回答

1

要獲取子集合,您可以聲明一個實體圖。事情是這樣的:

@NamedEntityGraph(
    name = "parent.withChildren", 
    attributeNodes = { 
      @NamedAttributeNode("children") 
    } 
) 

然後與資料庫的方法使用它:

@EntityGraph("parent.withChildren") 
Page<Parent> findWithChidren(Pageable page); 
+0

這是我推薦的解決方案! 我知道有一種不同的方法來執行它,調用「getChild」,但是如果你需要這樣做的話,你會很困惑,所以連接沒有關閉,避免了Lazy異常。使用JPA 2.1解決方案保持簡單。爲贏得命名實體圖! –

+0

謝謝!它真的解決了我的問題! –