我正在使用springBoot
,我想将OneToMany
的关系从父母映射到孩子。直接将entity
与eager
一起使用会获取递归记录,因此,尝试对ModelMapper
使用DTO
映射到Entity
,但是我无法弄清楚去做吧。请假设getters
和setters
。
Parent.java
@Entity
public class Parent {
@Id
private int parentId;
private String a;
@OneToMany(mappedBy = "parent")
private Set<Child> child;
Child.java
@Entity
public class Child {
@Id
private int childId;
private String c;
@ManyToOne
@JoinColumn(name = "b")
private Parent parent;
我有使用findAll
方法的有效存储库和服务层。
ParentDto.java
public class ParentDto {
private String a;
private Set<Child> child;
ParentController.java
@RestController
public class ParentController {
@Autowired
private ModelMapper modelMapper;
@Autowired
private ParentService parentService;
@RequestMapping(method = RequestMethod.GET, value="/parents" )
public List<ParentDto> getParents() {
List<Parent> parents = parentService.getAll();
return parents.stream()
.map(x-> modelMapper.map(x, ParentDto.class))
.collect(Collectors.toList());
}
}
错误::尝试获取http://localhost:8080/parents
.
.
ModelMapper mapping errors: 1) Converter org.modelmapper.internal.converter.CollectionConverter@51381583 failed to convert java.util.Set to java.util.Set. 1 error
org.modelmapper.MappingException: ModelMapper mapping errors:
1) Converter org.modelmapper.internal.converter.CollectionConverter@51381583 failed to convert java.util.Set to java.util.Set.
1 error
at org.modelmapper.internal.Errors.throwMappingExceptionIfErrorsExist(Errors.java:380)
at org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:80)
.
.
答案 0 :(得分:0)
这与“ N + 1”和“无限递归”无关,可以在映射器中添加Conver方法; 使用ModelMapper映射子级 https://amydegregorio.com/2018/10/03/mapping-children-with-modelmapper/
答案 1 :(得分:-1)
您需要在定义的父映射上使用@JsonIgnore批注 在您的孩子实体中。
有关更多信息,请参阅此文档- https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonIgnore.html