简体   繁体   中英

How to map oneToMany using ModelMapper

I am using springBoot , I want to map OneToMany relationship from parent to child. Directly using entity with eager fetching I get recursive records, therefore, trying using ModelMapper for DTO mapping to Entity but I am not able to figure out how to do it. Please assume getters and 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;

I have working repository and servicelayer with findAll method.

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

Error: While trying to fetch 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)
.
.

这与“N + 1”和“无限递归”问题无关,可能会在mapper中添加Conver方法; 使用ModelMapper映射Children https://amydegregorio.com/2018/10/03/mapping-children-with-模型映射器/

I propose "Preferred nested properties".
http://modelmapper.org/user-manual/configuration

You need to use @JsonIgnore annotation on the parent mapping defined in your child entity.

Refer this documentation for more info - https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonIgnore.html

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