目标属性匹配多个源属性层次结构 - SpringBoot、ModelMapping

时间:2021-03-14 21:57:13

标签: java spring-boot modelmapper

我正在尝试将租借书籍的列表添加到我的数据库中。

我在 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()

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

这是我找到的解决方案。

将此行添加到我的 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

答案 1 :(得分:0)

在您的 @Id 字段中添加一个 rentId 注释,sp spring 知道哪个是 id,也可以用于搜索等:

public class RentDto {

    @Id
    private Long rentId;

    //...
}