Issue
I have a Parent User Class that has multiple ManyToMany Relationships.
@Table(name = "user")
public class User {
..
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.DETACH})
@JoinTable(
name = "user_address",
joinColumns = { @JoinColumn(name = "user_id")},
inverseJoinColumns = { @JoinColumn(name = "address_id")}
)
@JsonIgnore
private final List<Address> addresses = new ArrayList<Address>();
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.DETACH})
@JoinTable(
name = "reports",
joinColumns = { @JoinColumn(name = "user_id")},
inverseJoinColumns = { @JoinColumn(name = "reports_id")}
)
@JsonIgnore
private final List<Reports> reports = new ArrayList<Reports>();
}
When I access the FIRST ManyToMany property, everything works fine. However, immediately after accessing the first, when I try to access the SECOND ManyToMany Property I get the "could not initialize proxy - no Session" exception:
@Component
public class Combiner {
public void combineData() {
...
List<Address> addresses = user.getAddress(); // This works
List<Reports> reports = user.getReports(); // Get the error here
..
}
}
The Address
and Reports
classes have the inverse relationship as many ManyToMany back to the User
Entity Above.
public class Address {
@ManyToMany(mappedBy = "addresses", fetch = FetchType.LAZY)
private final List<User> users = new ArrayList<User>();
}
public class Reports {
@ManyToMany(mappedBy = "reports", fetch = FetchType.LAZY)
private final List<User> users = new ArrayList<User>();
}
I tried searching SO for the same error where there are MULTIPLE relationships like mine and the first passes but second fails, but could'nt find a post (or google couldn't understand the search terms, if anyone knows a pre-existing one - please let me know). Could someone assess what else Im missing?
I've tried these so far to no avail:
- Added @Transactional to the parent Service class that calls
Combiner
above - Made the second failing relationship
EAGER
. (as i understand it you cant make BOTH EAGER since i get a multiple bags error probably because of Cartesian join)
AM Using SpringBoot (2.2.4) with Hibernate Core {5.4.10.Final}
Solution
Approach one:
Make @ManyToMany
uni-directional. The exception clearly says it can not initialize the collection of role
you have in User
class.
As you asked in the comment section Why can't this use case be Bi Directional - You can make this bi-directional
as well.
Approach two: make collection of role
EAGER or use Hibernate.initialize()
to initialize the collection.
Bonus: you can make both collection
EAGER
by using Set
not List
.
Answered By - Erfan Ahmed