1

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);
            }
    }
Nunyet de Can Calçada
  • 3,615
  • 32
  • 127
  • 219
  • Possible duplicate of [org.hibernate.LazyInitializationException - could not initialize proxy - no Session](https://stackoverflow.com/questions/21574236/org-hibernate-lazyinitializationexception-could-not-initialize-proxy-no-sess) – Shantaram Tupe Feb 27 '18 at 10:08

1 Answers1

0

But I don't know how to add a new Hotel avoiding this error

When you try to add a new hotel, you are trying to make a new transaction to the database as well, therefore you need to have an open session so you can make this transaction.

I see that you are using Spring so what you can do here is to add a @transactional annotation to the method where you are trying to add a new favorite hotel.

@Transactional
public void addNewHotel(Hotel hotel){
   Hibernate.initialize(loggedInUser().getFavoriteHotels());
   loggedInUser().getFavoriteHotels().add(hotel);
}
cнŝdk
  • 28,676
  • 7
  • 47
  • 67