What's a workaround if I have a relation OneToMany
and would like to access the collection that is lazy loaded? Currently I get LazyInitializationException
having this:
Club
entity:
@Entity
public class Club {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "club", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JsonBackReference
private List<Player> players;
Player
entity:
Is it a good idea to have two methods, where one fetches data without players and the second one that fetches also players?
@Override
List<Club> findAll();
@Query("Select clubs from Club clubs left join fetch clubs.players")
List<Club> getAllClubsWithPlayers();
What I'm thinking of is that it is a bad idea, because if I have a situation where I have for example 4 properties that are lazy loaded and I'd need at once 3 of them, I'd have to have a query like: getAllClubsWithPlayersAndSponsorsAndCoaches
, so I'd have to have a lot of combinations of such queries.
I don't want to use EAGER
, so could you tell me if it's a common way to do this if I need access to players
from the Club
sometimes which is undoable with the findAll()
method that throws LazyInitializationException
?
Don't get me wrong - I know where the LazyInitializationException
comes from, but I just don't know what's the best way to get access to players
if I sometimes need them when fetching clubs
. Is my way of doing it correct?