Reputation: 980
I am designing the model of a DB:
@Entity
@Table(name="t_urna")
public class Urna implements Serializable {
@OneToMany(mappedBy = "urna",
cascade = CascadeType.ALL,
orphanRemoval = true, fetch = FetchType.EAGER)
@JsonIgnore
private Set<Vot> vots = new HashSet<>();
..
}
@Entity
@Table(name="t_vot")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Vot implements Serializable {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "urna_id")
@JsonIgnore
Urna urna;
}
and I was wondering if setting FetchType.EAGER in both classes could cause a problem, like an ever ending loop or some stackoverflow.... and if it is a good practice
Upvotes: 0
Views: 140
Reputation: 3805
No, you will not have a neverending loop.
I don't think there is good or bad practices at this level. Sometimes it is better to use LAZY, because it prevent you from loading objects you don't need. Sometimes it is better to use EAGER, as it will prevent hibernate from running multiple requests if you need the objects.
When programming microservices, I always use EAGER (et bounded context aggregate). For a monolith, maybe LAZY is wiser.
Upvotes: 1
Reputation: 961
Default fetch type for @ManyToOne
is EAGER
anyway. If you set it on the @OneToMany
it shouldn't end up with stack overflow.
If it is a good practice? I wouldn't say yes, but there are times when you need to fetch also related entities. But I would say it's always better to specify entity graph
Upvotes: 0