【发布时间】: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 中创建了两个表 recipestest 和 ingredients(尤其是):
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)
)
Recipe 和 Ingredient 都有存储库:
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)
【问题讨论】:
标签: java database postgresql spring-boot