如何解决目标属性匹配多个源属性层次结构 - SpringBoot、ModelMapping
我正在尝试将租借书籍的列表添加到我的数据库中。
我在 SpringBoot 中使用 ModelMaper。
代码如下:
RentDto.java
@Getter
@Setter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
public class RentDto {
private Long rentId;
private Long userId;
private Long bookId;
private String userFirstName;
private String userLastName;
private String bookTitle;
private LocalDateTime rentStart;
private LocalDateTime RentEnd;
}
RentController.java
@ApiOperation(value = "Add Multiple Rents")
@PostMapping("/addMultipleRent")
@ResponseStatus(HttpStatus.CREATED)
public void addMultipleRent(@RequestBody List<RentDto> rentDto){
rentService.addMultipleRents(rentDto);
}
RentService.java
public void addMultipleRents(List<RentDto> rentDto){
rentRepository.saveAll(mapRentListDtoToRentList(rentDto));
}
//Convert List of books to List of bookDto
private List<Rent> mapRentListDtoToRentList(List<RentDto> rents) {
return rents.stream()
.map(rent -> modelMapper.map(rent,Rent.class))
.collect(Collectors.toList());
}
我收到以下错误:
1) The destination property com.example.library.entity.Rent.setId() matches multiple source property hierarchies:
com.example.library.dto.RentDto.getRentId()
com.example.library.dto.RentDto.getUserId()
com.example.library.dto.RentDto.getBookId()
感谢任何帮助。
解决方法
这是我找到的解决方案。
将此行添加到我的 addMultipleRents()
方法中。
List<Rent> rent = Arrays.asList(modelMapper.map(rentDto,Rent.class));
添加后 RentService.java 看起来像这样:
public void addMultipleRents(List<RentDto> rentDto){
List<Rent> rent = Arrays.asList(modelMapper.map(rentDto,Rent.class));
rentRepository.saveAll(rent);
}
我完全删除了方法 mapRentListDtoToRentList
。
在您的 @Id
字段中添加一个 rentId
注释,sp spring 知道哪个是 id,也可以用于搜索等:
public class RentDto {
@Id
private Long rentId;
//...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。