0

I'm having 3 entities City, Hotel and BookRoom with mapping as mentioned below:

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<City> cities;

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "hotel")
  private Set<BookRoom> bookRoom;
}

public class City {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int cityID;
  ....
  ....
  @ManyToMany(fetch = FetchType.LAZY, mappedBy = "cities")
  private Set<Hotel> hotels;
}

And I'm using CRUD Repository for persisting

public interface BookRoomRepo extends CrudRepository<BookRoom, Integer> {
}

Now I have a existing data for hotel and city. So while calling save() method of bookroom I'm getting:

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.hbs.entity.Hotel

And my method for calling is as below:

@Override
public void run(String... arg0) throws Exception {
    City city = new City();
    Hotel hotel = new Hotel();
    city.setCityID(4);
    Set<City> cities = new HashSet<>();
    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);
}

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.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
AMAN KUMAR
  • 277
  • 1
  • 6
  • 19
  • Possible duplicate of [JPA/Hibernate: detached entity passed to persist](http://stackoverflow.com/questions/13370221/jpa-hibernate-detached-entity-passed-to-persist) – Arpit Aggarwal Jan 11 '17 at 07:42

1 Answers1

0

Try using the merge() method, and not the save() method. See https://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa/

Essex Boy
  • 7,565
  • 2
  • 21
  • 24