简体   繁体   中英

Spring data JPA updates one/many-to-many relationship using Beanutils.copyProperties

I have two classes with one-to-many relationship.

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

To update the existing hotel in the database, do I have to retrive one by one the existing meeting from meeting database table and assign new time and number, then assign the meeting list to the hotel? If not, how do I resolve the reference exception after I copy a list through BeanUtils.copyProperties eg

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

Is there a better way to update the object with the relationship?

In order to update the hotel you should just load it from database, update what you want and save it

Hotel hotel = hotelDao.findById(hotelDto.getId());
hotel.getMeetings().add(newMeeting); 
hotelDao.saveAndFlush(hotel);

BeanUtils is a good API to use, but it does kind of shallow object mapping. It doesn't do a good job when working with the objects that contain in other objects and figuring out their data types.Use ModelMapper instead of BeanUtils.Also ModelMapper uses TypeTokens to allow mapping of generic parameterized types. if you wonder how it works you can read the documentation from this link http://modelmapper.org/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM