JPA/Hibernate Parent/Child relationship
- by NubieJ
Hi
I am quite new to JPA/Hibernate (Java in general) so my question is as follows (note, I have searched far and wide and have not come across an answer to this):
I have two entities:
Parent and Child (naming changed).
Parent contains a list of Children and Children refers back to parent.
e.g.
@Entity
public class Parent {
@Id
@Basic
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PARENT_ID", insertable = false, updatable = false)
private int id;
/* ..... */
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", nullable = true)
private Set<child> children;
/* ..... */
}
@Entity
public class Child {
@Id
@Basic
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CHILD_ID", insertable = false, updatable = false)
private int id;
/* ..... */
@ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID")
private Parent parent;
/* ..... */
}
I want to be able to do the following:
Retrieve a Parent entity which would contain a list of all its children (List), however, when listing Parent (getting List, it of course should omit the children from the results, therefore setting FetchType.LAZY.
Retrieve a Child entity which would contain an instance of the Parent entity.
Using the code above (or similar) results in two exceptions:
Retrieving Parent:
A cycle is detected in the object graph. This will cause infinitely deep XML...
Retrieving Child:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: xxxxxxxxxxx, no session or session was closed
When retrieving the Parent entity, I am using a named query (i.e. calling it specifically)
@NamedQuery(name = "Parent.findByParentId", query = "SELECT p FROM Parent AS p LEFT JOIN FETCH p.children where p.id = :id")
Code to get Parent (i.e. service layer):
public Parent findByParentId(int parentId) {
Query query = em.createNamedQuery("Parent.findByParentId");
query.setParameter("id", parentId);
return (Parent) query.getSingleResult();
}
Why am I getting a LazyInitializationException event though the List property on the Parent entity is set as Lazy (when retrieving the Child entity)?