2016-06-07 23 views
0

/**父實體**/延遲加載與QueryDsl /休眠不工作

@Entity 

@Table(name = "Parent") 

public class Parent { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy = IDENTITY) 
    @Column(name = "parentId", unique = true, nullable = false) 
    private Integer parentId; 


    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent") 
    @JsonManagedReference 
    private Set<Child> childs = new HashSet<Child>(0);  

} 

******子實體******

@Entity 

@Table(name = "Child") 

public class Child { 

private static final long serialVersionUID = 1L; 

    @ManyToOne(fetch = FetchType.LAZY, targetEntity = Parent.class) 
    @JoinColumn(name = "GuestID") 
    @JsonBackReference 
    private Parent parent; 

} 

當我試圖檢索父細節,它也獲取子記錄,這應該不會發生,因爲我提供了FetchType.LAZY。

*********** DAO類*******

public class ParentRepositoryImpl implements ParentRepository { 

    public final List<Parent> retrieveParentList(){ 

    QParent qParent = QParent.parent; 
    JPQLQuery<Parent> query = new JPAQuery<Parent>(em); 
    List<Parent> parents = query.from(qParent).fetch(); 
    } 
} 

此外,我希望有條件(收費)取子記錄,我怎麼能實現這個?

回答

0

做了一些研究之後,我發現了必要的變通下面這裏,

其實,REST API需要序列數據,並通過線路發送。就我而言,我使用Jackson將Java對象序列化爲JSON格式。默認情況下,Jackson ObjectMapper沒有意識到Hibernate和它的延遲加載方案。在序列化過程中,Jackson正在觸及導致Hibernate讀取所有數據的實體的所有屬性,從而失去了從Lazy Loading獲得的好處。

爲了避免這種情況,我們需要實施jackson-module-hibernate

「此模塊支持Hibernate特定數據類型和屬性的JSON序列化和反序列化,尤其是延遲加載方面。」隨着此模塊的添加,Jackson不再嘗試序列化Lazy Loaded集合。