DamienMiheev
DamienMiheev

Reputation: 1047

Why does not FetchType.Lazy work?

I have model Category. It may have parent Category and list of sub Category. I wrote this questions because could not find case where entity relate to himself.

I tried to implement it like this:

@Entity
public class Category {
@Id
private String id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Category parent;

@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private List<Category> subcategories = Lists.newArrayList();
}

I save entities like:

Category parent = new Category();
parent.setName("parent");

Category child1 = new Category();
child1.setName("child1");
child1.setParent(parent);

parent.getSubcategories().add(child1);

categoryPersistence.save(parent);

I expected to see something like:

parent {
id
parent: null
childs {
   child {
      id
      parent: ...lazy loading exception...
      childs: null
   }
}
}

But in child model on filed parent i have recursive loop. How to prevent it?

Yeah, i also used @JsonIgnore. But i was not sure is it good practice. But if i have a case when i need one Category and i realy need to send it to UI with parent. Is @JsonIgnore can produce this?

Upvotes: 2

Views: 1501

Answers (1)

Naresh Joshi
Naresh Joshi

Reputation: 4537

@damienMiheev I have also suffered from same problem, but debugging the issue 1 or half hour i figured out

That even if your parent field loaded lazily, while the automatic JSON generation getter of your field is getting called which is fetching the values, which is creating some cyclic execution. Because it is fetching parent then fetching children and again fetching parent for every child in children collection and continuing this process until StackOverflows.

Here are the solution for your problem

You should exclude the "parent" the from json generation e.g. you can mark that field as @JsonIgnore. you should also not include parent and children in your hashCode(), equals() and toString() method.

Upvotes: 2

Related Questions