我有两个具有一对多关系的班级。
class Hotel {
private String name;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Meeting> meetings = new ArrayList<>();
}
class Meeting {
@Column(name = "meeting_time")
@NotNull
private LocalDateTime meetingTime;
@Column(name = "number_people")
@NotNull
@Min(1)
private int numberPeople;
}
class HotelDto{
private long id;
private List<MeetingDto> meetingDtos;
}
class MeetingDto {
private long id;
private LocalDateTime meetingTime;
private int numberPeople;
}
要更新数据库中的现有旅馆,我是否必须从会议数据库表中逐个检索现有会议并分配新的时间和号码,然后将会议列表分配给旅馆?如果没有,我通过BeanUtils.copyProperties
复制列表后如何解决引用异常
例如
Hotel newHotel = new Hotel();
Hotel hotel = hotelDao.findById(hotelDto.getId());
List<Meeting> newMeetingList = new ArrayList<>();
for (MeetingDto mDto : hotelDto.getMeetingDtos()) {
Meeting meeting = meetingDao.findById(mDto.getId());
meeting.setMeetingTime(mDto.getMeetingTime());
meeting.setNumberPeople(mDto.getNumberPeople());
// meetingDao.saveAndFlush(meeting); should I add this?
newMeetingList.add(meeting);
}
newHotel.setMeetings(newMeetingList);
BeanUtils.copyProperties(newHotel, hotel, "id");
hotelDao.saveAndFlush(hotel);
有没有更好的方法来更新具有关系的对象?
答案 0 :(得分:0)
要更新酒店,您只需从数据库中加载酒店,更新所需内容并保存
Hotel hotel = hotelDao.findById(hotelDto.getId());
hotel.getMeetings().add(newMeeting);
hotelDao.saveAndFlush(hotel);