在子表的双向一对多ModelMapper集父ID

时间:2019-01-30 15:35:29

标签: hibernate spring-boot jpa modelmapper

我在Springboot中使用ModelMapper,并且试图在子表中设置父ID,但是父ID继续为null。

现在,我了解了在休眠状态下您需要像这样在子级中设置父级对象。

class Parent {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<Child> childs;

    //getters / setters
}

class Child {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="parent_id")
    private Parent parent;

    //getters / setters
}

method() {
    Child child = new Child();
    child.setName("fred");
    Parent parent = new Parent();
    parent.setName("teddy");

    child.setParent(parent);

    Set<Child> childs = new ArrayList<>();
    childs.add(child);

    parent.setChilds(childs);

    session.save(parent)
}

但是;我要寻找的是让ModelMapper句柄在子类中自动设置父属性,而不是手动设置父字段。

我有以下DTO。

class ParentDTO {
    private Long id;
    private List<ChildDTO> childs;

    //getters / setters
}

class ChildDTO {
    private Long id;
    private String name;
    private ParentDTO parent;

    //getters / setters
}    

像这样使用ModelMapper

public ParentDTO post(@RequestBody ParentDTO parentDTO) {

   ModelMapper modelMapper = new ModelMapper();
   Parent parent = modelMapper.map(parentDTO, Parent.class);

   parentRepository.save(parent)
   .....
}

我还想补充一点,我正在使用SpringBoot,并且像这样用JSON RequestBody填充我的DTO对象

{
    "name" : "teddy",
    "child": [
        {
           "name": "fred",
        }
    ]
}

保存结果

{
    "id" : 1
    "name" : "teddy",
    "child": [
        {
           "parent" null
           "name": "fred",
        }
    ]
}

有一种简单的方式来设置使用子对象中的父值ModelMapper?

0 个答案:

没有答案