I am facing an issue where the data is getting fechted recursively. I wanted to avoid the child to fetch the parent data. Which is causing a recursive issue. I have mentioned the code below
Pojo Structure
class Parent {
..
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private List<Child> childs;
..
}
class Child {
..
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parentId")
private Parent parent;
..
}
Fetching the data like this
` em = EMF.get().createEntityManager();
Query q = em.createQuery("Select p from Parent p", Parent.class);
List<Parent> parents = q.getResultList();
// Till this point all looks good but when the code gets executed
parent.getChilds();
`
It is fetching the data like this:
Parent
child1
Parent
child2
Parent
child2
Parent
..
..
child2
..
Which I dont need I just want the data like this:
Parent1
child1
child2
Parent2
child1
child2
child3
While
FetchType.EAGERis a contract,FetchType.LAZYis only a hint, because lazy fetching is not always possible. This may depend e.g. on the JPA provider you use as well as on its configuration. Lazy fetching is particularly problematic with to-one relationships.If every
Childhas aParent, try addingoptional=falseto your@ManyToOne. This might enable lazy fetching.Since the
Parententity is already loaded into the persistence context, populatingChildren.parentshouldn't trigger queries against the database. Are you actually seeing queries being executed? How do you knowChildren.parentis being loaded? If you are accessing the value to check that fact, chances are you are actually triggering the on-demand loading yourself.