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.
Try using the merge() method, and not the save() method. See https://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.