【问题标题】:Spring Boot - null value in foreign key PostgreSQL databaseSpring Boot - 外键 PostgreSQL 数据库中的空值
【发布时间】:2020-04-18 16:29:28
【问题描述】:

我有Recipe 类:

@Entity
@Table(name="recipestest")
public class Recipe {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String title;

    private String description;

    @OneToMany(mappedBy="recipe")
    private List<Ingredient> ingredients;

    public Recipe(String title, String description, List<Ingredient> ingredients) {
        this.title = title;
        this.description = description;
        this.ingredients = ingredients;
    }

    public Recipe() { }

    /* getters and setters */
}

还有Ingredient类:

@Entity
@Table(name="ingredients")
public class Ingredient {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    private int quantity;

    private String unit;

    @ManyToOne
    @JoinColumn(name="recipe_id", nullable=false)
    private Recipe recipe;

    public Ingredient(String name, int quantity, String unit) {
        this.name = name;
        this.quantity = quantity;
        this.unit = unit;
    }

    public Ingredient() { }

    /* all getters and setters */
}

我在 PostgreSQL 中创建了两个表 recipestestingredients(尤其是):

CREATE TABLE ingredients (
    id bigserial NOT NULL PRIMARY KEY,
    name text NOT NULL,
    quantity integer NOT NULL,
    unit text NOT NULL,
    recipe_id integer NOT NULL REFERENCES recipestest(id)
)

RecipeIngredient 都有存储库:

public interface RecipeRepository extends JpaRepository<Recipe, Long> {
}

public interface IngredientRepository extends JpaRepository<Ingredient, Long> {
}

有这个createRecipe - 在数据库中存储对象的方法:

@PostMapping(path = "")
public Recipe createRecipe(@RequestBody Recipe recipe) {
    ingredientRepository.saveAll(recipe.getIngredients());
    return recipeRepository.save(recipe);
}

我在 Postman 中通过 POST 传输这个 JSON:

{
    "title": "cake1",
    "description": "description1",
    "ingredients": [
        {
            "name": "ingredient1",
            "quantity": 8,
            "unit": "g"
        },
        {
            "name": "ingredient2",
            "quantity": 8,
            "unit": "ml"
        }
    ]
}

我想将ingredients 表中的recipe_id 设为各自recipetest 实体的id,但我遇到了这样的错误:

{
    "timestamp": "2019-12-29T18:06:07.979+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
}

IntelliJ IDEA 的终端出错:

org.postgresql.util.PSQLException: ERROR: null value in column "recipe_id" violates not-null constraint
Detail: Failing row contains (47, ingredient1, 8, g, null)

我的application.propertiespom.xml

【问题讨论】:

    标签: java database postgresql spring-boot


    【解决方案1】:

    您正在使用:

    @JoinColumn(name = "recipe_id", nullable = false)
    private Recipe recipe;
    

    这意味着Recipe不应该为空,但是正如我们在您的JSon文件中看到的那样,只有Ingredients的列表没有Recipes,这导致了这个问题。


    有很多方法,其中一种是使用CascadeType.PERSISTCascadeType.ALL,具体取决于您想要做什么:

    @OneToMany(mappedBy="recipe", cascade = CascadeType.PERSIST)
    private List<Ingredient> ingredients;
    

    那么在你的服务中你只能保存配方:

    @PostMapping(path = "")
    public Recipe createRecipe(@RequestBody Recipe recipe) {
        //ingredientRepository.saveAll(recipe.getIngredients());
        return recipeRepository.save(recipe);
    }
    

    建议

    对于必须使用 Long 的 id,它接受 null,而不是原始类型:

    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2020-12-10
      • 2020-08-28
      • 1970-01-01
      相关资源
      最近更新 更多