簡體   English   中英

保持具有雙向關系的嵌套實體(一對多)

[英]Persist nested entities (one-to-many) with a bidirectional relationship

I am creating a Spring Boot web application that is supposed to receive a JSON document via HTTP, parse it to the respective entity class, and persist the object. JSON 是一個配方實例的表示,一個配方可以有多個與之關聯的步驟對象。

配方.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
}

步驟.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 文檔時,在步驟 object 中引用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 來進行持久性。

在您的 controller 中,您將不得不這樣做。

for (Step step : recipe.getSteps()) {
    step.setRecipe(recipe);
}

當您發布時,您基本上缺少Step object中的反向引用,即null

您可以在@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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM