I have a User class containing a collection of lazy loaded objects.
class User {
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@Getter
@Column(nullable = false)
private List<Wallet> wallets= new ArrayList<>();
}
Now I also have a Transaction class which contains a reference to the User's wallet.
class Transaction {
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "senderWallet", referencedColumnName = "id")
private Wallet senderWallet;
}
Now I created a service which is supposed to fetch the transactions for a given user:
@Transactional
public List<Transaction> getTransactionsForUser(User user) {
List<Wallet> wallets = user.getWallets();
List<Transaction> transactions = new ArrayList<>();
for (Wallet wallet : wallets) {
transactions.addAll(transactionRepository.findBySenderWallet(wallet));
}
return transactions;
}
In the controller, I'm fetching the current logged in user like this:
User user = ((UserPrincipal) authentication.getPrincipal()).getUser();
Afterwards, I make a call to the service:
List<Transaction> transactions = transactionService.getTransactionsForUser(user);
And this throws a LazyInitializationException. What's the workaround here?