Spring数据JPA使用父对象ID保存子对象
我有两个对象,一个是父对象,一个是子对象,如下所示:Spring数据JPA使用父对象ID保存子对象,spring,database,spring-data-jpa,persistence,h2,Spring,Database,Spring Data Jpa,Persistence,H2,我有两个对象,一个是父对象,一个是子对象,如下所示: @Entity @Table(name="category") public class CategoryModel { private @Id @GeneratedValue Long id; private String name; @OneToMany(mappedBy="category", cascade=CascadeType.PERSIST) priva
@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;
}
public Long createCategory(CategoryDto categoryDto) {
CategoryModel categoryModel = categoryDto.toModel(true,true);
categoryModel.getAttributes().forEach(a -> a.setCategory(categoryModel));
return categoryRepository.save(categoryModel).getId();
}
如何使用在属性值之前创建的类别id将属性值持久化到数据库中?首先,这个问题不是“Spring数据JPA”问题,而是JPA(可能是Hibernate)问题
分析 由于您遗漏了控制器和JSON映射的代码,我不得不猜测一下:
- 事实1:类别和属性之间的关系由属性
控制,而不是由AttributeModel.category
控制。(这就是JPA的工作原理)。CategoryModel.attributes
- 观察2:您的JSON对象定义
(即与JPA的工作方式相反)CategoryModel.attributes
AttributeModel.category
字段。
解决方案 因此,您需要指示JSON映射器在反序列化过程中设置
AttributeModel.category
字段。如果您使用Jackson,您可以使用:
和@JsonManagedReference
@JsonBackReference
我通过手动设置子对象对父对象的引用来解决此问题,如下所示:
@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;
}
public Long createCategory(CategoryDto categoryDto) {
CategoryModel categoryModel = categoryDto.toModel(true,true);
categoryModel.getAttributes().forEach(a -> a.setCategory(categoryModel));
return categoryRepository.save(categoryModel).getId();
}
还请共享用于在数据库中持久化类别和属性的代码。我没有编写任何将实体保存到数据库的代码。我使用的是这样定义的crudepository:public interface CategoryRepository扩展了JpaRepository。我使用这个接口的save方法。您能显示您在服务中编写的代码吗?问题可能出在事务中。我是通过将属性模型设置为所需类别手动完成的,我认为您的建议是相同的。@cuneytyvz:“我是通过将属性模型设置为所需类别手动完成的,”您是在问问题之前还是在我的回答之后完成的,它解决了问题吗?--如果没有,请发布控制器和dao代码。我这样做了,后来看到了你的回复。我补充了一个答案。
public Long createCategory(CategoryDto categoryDto) {
CategoryModel categoryModel = categoryDto.toModel(true,true);
categoryModel.getAttributes().forEach(a -> a.setCategory(categoryModel));
return categoryRepository.save(categoryModel).getId();
}