I have a domain object called User with this property
@ManyToMany
@JoinTable(
name="t_user_fav_hotel",
joinColumns=@JoinColumn(name="user_id", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="hotel_id", referencedColumnName="id"))
private Set<hotel> favoriteHotels = new HashSet<>();
I've created a method in the service level to get all the favorites and avoid the error could not initialize proxy and it works fine.
userService.getFavorites (loggedInUser());
But I don't know how to add a new Hotel avoiding this error:
Hibernate.initialize(loggedInUser().getFavoriteHotels());
loggedInUser().getFavoriteHotels().add(hotel);
I also added in the user service level with the same result
@Transactional
public void addFavorite (User user, Hotel hotel) {
Hibernate.initialize(user.getFavoriteHotels());
if (!user.getFavoriteHotels().contains(hotel)) {
user.getFavoriteHotels().add(hotel);
userRepository.save(user);
}
}