问题
/** Parent Entity **/
@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);
}
****** The Child Entity ******
@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;
}
When i tried to retrieve Parent details, it also fetch child record, which should not be happen as i have provided FetchType.LAZY.
*********** DAO Class *******
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();
}
}
Also i want to conditionally (on request) fetch child record, how can i achieve this?
回答1:
After doing some study i found the necessary work around below here,
Actually, REST API needs to serialize data and send it across the wire. In my case, I'm using Jackson to serialize Java objects into JSON format. By default, the Jackson ObjectMapper has no awareness of Hibernate and it's Lazy Loading scheme. During the serialization process, Jackson was touching all the properties on the entity which resulted in Hibernate fetching all the data thereby losing the benefits gained from Lazy Loading.
To avoid this we need to implement jackson-module-hibernate.
"This module support JSON serialization and deserialization of Hibernate specific datatypes and properties; especially lazy-loading aspects." With the addition of this module, Jackson no longer tries to serialize Lazy Loaded collections.
来源:https://stackoverflow.com/questions/37681314/lazy-loading-with-querydsl-hibernate-not-working