猿问

Spring Data Rest 持久化注解

我正在学习 Spring-Data-REST 并且遇到了涉及我的注释的障碍。目前我有以下架构:


create table user

(

    ID int NOT NULL auto_increment, 

    NAME VARCHAR(60) NOT NULL,

    PASS VARCHAR(20) NOT NULL,

    primary key (ID)

);


create table recipe

(

    ID int NOT NULL auto_increment,

    NAME varchar(60) NOT NULL, 

    USER_ID int NOT NULL,

    primary key (ID),

    FOREIGN KEY (USER_ID) REFERENCES user(ID) ON DELETE CASCADE

);


create table ingredient

(

    ID int not null auto_increment,

    NAME varchar(60) not null,

    primary key(ID)

);


create table ingredientsList 

(

    ID int NOT NULL auto_increment,

    NAME varchar(60) NOT NULL,

    RECIPE_ID int not null,

    INGREDIENT_ID int not null,

    QUANTITY int not null,

    primary key (ID),

    foreign key (RECIPE_ID) REFERENCES recipe(ID) on delete cascade,

    foreign key (INGREDIENT_ID) references ingredient(ID) on delete cascade

);


create table direction

(

    ID int NOT NULL auto_increment,

    NAME varchar(60) NOT NULL,

    RECIPE_ID int not null,

    STEP int not null,

    DESCRIPTION varchar(256),

    primary key (ID),

    foreign key (RECIPE_ID) REFERENCES recipe(ID) on delete cascade

);

我的 Spring Data REST API 中表示了每个表,除了一个表,即成分列表表。这是我当前的实现,当我运行 .\mvn clean install 时无法正常工作:


import java.util.Objects;

import java.util.Set;


import javax.persistence.Column;

import javax.persistence.CascadeType;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.OneToMany;


@Entity

public class IngredientsList extends AbstractEntity {


    @ManyToOne(fetch = FetchType.EAGER)

    @JoinColumn(nullable=false)

    private Recipe recipe;

    @OneToMany(mappedBy = "ingredientsList", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)

    private Set<Ingredient> ingredients;

    @Column(nullable = false)

    private Long quantity;


    public Recipe getRecipe() {

        return recipe;

    }


    public void setRecipe(Recipe recipe){

        this.recipe = recipe;

    }


繁星coding
浏览 149回答 2
2回答

森栏

您@OneToMany对IngredientsList类的注释暗示类中应该有一个ingredientsList字段Ingredient,而实际上没有。在您的架构中,您INGREDIENT_ID的ingredientsList表中有一个字段,这意味着 anIngredientsList只能有一个Ingredient.我认为你的意思是IngredientsList有很多Ingredient孩子,这意味着ingredient表应该有一个INGREDIENT_LIST_ID字段作为ingredientsList表的外键,并且Ingredients类应该有一个ingredientsList字段。该INGREDIENT_ID字段应该从ingredientsList表中删除。如果一个IngredientsList应该只有一个Ingredient,那么改变@OneToMany(mappedBy = "ingredientsList", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)private Set<Ingredient> ingredients;到@ManyToOne@JoinColumn("ingredient_id")private Ingredient ingredient根据需要添加cascade和orphanRemoval。@ManyToOne默认情况下,A应该急切地获取连接的数据。
随时随地看视频慕课网APP

相关分类

Java
我要回答