【问题标题】:JPA or CRUD Repository query in spring boot for many to many relation for persisting dataSpring Boot 中的 JPA 或 CRUD 存储库查询用于持久数据的多对多关系
【发布时间】:2017-01-11 06:54:23
【问题描述】:

我有 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 存储库进行持久化

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 详细信息时,它会尝试添加酒店和城市的记录,不管数据是否存在。

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 2018-01-13
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2020-03-29
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多