gpt4 book ai didi

java - 保留具有双向关系的嵌套实体(一对多)

转载 作者:行者123 更新时间:2023-12-02 03:01:25 24 4
gpt4 key购买 nike

我正在创建一个 Spring Boot Web 应用程序,该应用程序应该通过 HTTP 接收 JSON 文档,将其解析为相应的实体类,并保留该对象。 JSON 是 Recipe 实例的表示,一个配方可以有多个与其关联的 Step 对象。

Recipe.java

@Entity
public class Recipe {

@Id
@GeneratedValue
private Long id;

@NotNull
private String name;

@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL)
private Set<Step> steps;

// Additional attributes, constructors, getters and setters omitted
}

Step.java

@Entity
public class Step {

@Id
@GeneratedValue
private Long id;

@NotNull
private String name;

@ManyToOne
@JoinColumn(name = "RECIPE_ID")
private Recipe recipe;

// Additional attributes, constructors, getters and setters omitted
}

但是,当将以下 JSON 文档发送到应用程序时,外键引用 RECIPE_ID步骤对象内是 null ,因此配方与其步骤之间没有联系。

{
"name": "Test recipe",
"description": "Test description",
"type": "Test",
"cookingTime": 45,
"preparationTime": 30,
"thumbnail": "",
"steps": [
{
"number": 1,
"name": "First step",
"content": "Test content",
"image": ""
},
{
"number": 2,
"name": "Second step",
"content": "Test content",
"image": ""
}
]
}

CascadeType.ALL 起,嵌套步骤对象不应该也被持久化吗?已指定?另外,我正在使用 RestController处理请求和 JpaRepository坚持不懈的类(class)。

最佳答案

您可以在@ManyToOne端添加@JsonBackReference注释,在@OneToMany端添加@JsonManagedReference注释。

@Entity
public class Recipe {

@Id
@GeneratedValue
private Long id;

@NotNull
private String name;

@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL)
@JsonManagedReference("recipe_steps")
private Set<Step> steps;

// Additional attributes, constructors, getters and setters omitted
}


@Entity
public class Step {

@Id
@GeneratedValue
private Long id;

@NotNull
private String name;

@ManyToOne
@JoinColumn(name = "RECIPE_ID")
@JsonBackReference("recipe_steps")
private Recipe recipe;

// Additional attributes, constructors, getters and setters omitted
}

关于java - 保留具有双向关系的嵌套实体(一对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61390098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com