title: JPA or CRUD Repository query in spring boot for many to many relation for persisting data
body: <p>I'm having 3 entities City, Hotel and BookRoom with mapping as mentioned below:</p>
  
  <pre><code>public class BookRoom {
  
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int bookID;
    .....
    .....
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name ="hotelID")
    private Hotel hotel;
  }  
  
  public class Hotel {
  
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer hotelID;
    ....
    ....
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "Hotel_City", joinColumns = @JoinColumn(name = "hotelID", nullable = false), inverseJoinColumns = @JoinColumn(name = "cityID", nullable = false))
    private Set&lt;City&gt; cities;
  
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "hotel")
    private Set&lt;BookRoom&gt; bookRoom;
  }
  
  public class City {
  
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int cityID;
    ....
    ....
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "cities")
    private Set&lt;Hotel&gt; hotels;
  }
  </code></pre>
  
  <p>And I'm using CRUD Repository for persisting</p>
  
  <pre><code>public interface BookRoomRepo extends CrudRepository&lt;BookRoom, Integer&gt; {
  }
  </code></pre>
  
  <p>Now I have a existing data for hotel and city.
  So while calling save() method of bookroom I'm getting:</p>
  
  <pre><code>Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.hbs.entity.Hotel
  </code></pre>
  
  <p>And my method for calling is as below:</p>
  
  <pre><code>@Override
  public void run(String... arg0) throws Exception {
      City city = new City();
      Hotel hotel = new Hotel();
      city.setCityID(4);
      Set&lt;City&gt; cities = new HashSet&lt;&gt;();
      cities.add(city);
      hotel.setCities(cities );
      hotel.setHotelID(2);
  
      BookRoom bookRoom = new BookRoom();
      bookRoom.setCheckInDate(new Date());
      bookRoom.setCheckOutDate(new Date());
      bookRoom.setCityN("Ranchi");
      bookRoom.setNoOfRooms(1);
      bookRoom.setHotel(hotel);
      bookRoom.setUserName("Aman");
      bookRoomRepo.save(bookRoom);
  }
  </code></pre>
  
  <p>So my issue is that while adding BookRoom detail will it try to add records for Hotel and City inspite of data exist or not.</p>