spring data jpa用父对象的id保存子对象

lvmkulzt  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(275)

我有两个对象,一个是父对象,一个是子对象,如下所示:

@Entity
@Table(name="category")
public class CategoryModel {
    private @Id @GeneratedValue Long id;

    private String name;

    @OneToMany(mappedBy="category", cascade=CascadeType.PERSIST)
    private List<AttributeModel> attributes;
}

@Entity
@Table(name="attribute")
public class AttributeModel {
    private @Id @GeneratedValue Long id;

    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="category_id")
    private CategoryModel category;
}

我也有Map到这些模型对象的DTO,但我推荐了它们。当我试图用这个有效负载保存一个category对象时,属性值也在attribute表中创建,但是类别id为空。

{
    "name":"Chemicals",
    "attributes":[
        {"name": "volume"}, {"name":"humidity"}
    ]
}

如何将属性值保存到数据库中,并使用在它们之前创建的类别id?

b5lpy0ml

b5lpy0ml1#

首先,这个问题不是“springdatajpa”问题,而是jpa(可能是hibernate)问题。

分析

由于您遗漏了控制器和jsonMap的代码,我不得不猜测:
事实1:类别和属性之间的关系由属性控制 AttributeModel.category 但不是通过 CategoryModel.attributes . (这就是jpa的工作原理)。
观察2:json对象定义 CategoryModel.attributes (即与jpa的工作原理相反)。
在不了解jsonMap配置和控制器代码的情况下,我猜问题是:jsonMap程序没有设置 AttributeModel.category 字段反序列化json对象。

解决方案

所以您需要指示jsonMap器设置 AttributeModel.category 反序列化期间的字段。如果你使用Jackson,你可以使用: @JsonManagedReference@JsonBackReference ```
@Entity
@Table(name="category")
public class CategoryModel {
...

@JsonManagedReference
@OneToMany(mappedBy="category", cascade=CascadeType.PERSIST)
private List<AttributeModel> attributes;

}

@Entity
@Table(name="attribute")
public class AttributeModel {
...

@JsonBackReference
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="category_id")
private CategoryModel category;

}

wr98u20j

wr98u20j2#

我通过手动设置子对象对父对象的引用来解决这个问题,如下所示:

public Long createCategory(CategoryDto categoryDto) {
    CategoryModel categoryModel = categoryDto.toModel(true,true);
    categoryModel.getAttributes().forEach(a -> a.setCategory(categoryModel));
    return categoryRepository.save(categoryModel).getId();
}

相关问题