2016-06-07 21 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集合。