Spring引导中的JPA或CRUD存储库查询,用于持久化数据的多对多关系

时间:2017-01-11 06:54:24

标签: java spring hibernate spring-boot spring-data-jpa

我有3个实体City,Hotel和BookRoom,其映射如下所述:

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;
}

我正在使用CRUD Repository来持久化

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

现在我有酒店和城市的现有数据。 因此,在调用bookroom的save()方法时,我得到了:

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

我的调用方法如下:

@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);
}

所以我的问题是,虽然添加BookRoom详细信息,但它会尝试为酒店和城市添加记录,尽管数据存在与否。

1 个答案:

答案 0 :(得分:0)

尝试使用merge()方法,而不是save()方法。见https://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa/