我的问题是关于下面的代码:
Ingredient.java
@Entity
@Table(name = "recipes_ingredients")
public class Ingredient implements Serializable {
@Id
@Column(name = "ingredient_id")
private Long id;
@NotEmpty
private String name;
private Integer quantity;
// Getters and Setters
}Recipe.java
@Entity
@Table(name = "recipes")
public class Recipe implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "recipe_id")
private Long id;
@NotEmpty
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Client client;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "fk_recipe_id")
private List<Ingredient> ingredients;
// Getters and Setters
}我想要做的是,PK (recipes_ingredients表)以某种方式由:ingredient_id和recipe_id组成(使用我已经拥有的,并使其也使用PK,或者只是以其他方式获取该ID,并将其改为PKE 215和ingredient_id)。
ingredient_id将是每个菜谱从1开始的数字,这样,如果我有一个recipe_id =1和3成分的配方,我的想法是,在配料表中有这样的内容:
ingredient_id(PK) name quantity recipe_id(PK)
1 Oil 150 1
2 Salt 5 1
3 Flour 500 1知道我该怎么做吗?
发布于 2021-03-26 15:30:18
public class IngredientId {
private Recipe recipe;
private Long id;
public IngredientId(Recipe recipe, Long id) {
this.recipe = recipe;
this.id = id;
}
public IngredientId() {
}
//Getters and setters are omitted for brevity
public Recipe getRecipe() {
return recipe;
}
public void setRecipe(Recipe recipe) {
this.recipe = recipe;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
IngredientId ingredientId = (IngredientId) o;
return Objects.equals( recipe, ingredientId.recipe ) && Objects.equals( id, ingredientId.id );
}
@Override
public int hashCode() {
return Objects.hash( recipe, id );
}
}
@Entity
@IdClass( IngredientId.class )
@Table(name = "recipes_ingredients")
public class Ingredient {
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "recipe_id")
private Recipe recipe;
@Id
@GeneratedValue
@Column(name = "ingredient_id")
private Long id;
private String name;
private Integer quantity;
public IngredientId getId() {
return new IngredientId( recipe, id );
}
public void setId(IngredientId id) {
this.recipe = id.getRecipe();
this.id = id.getId();
}
}
@Entity
@Table(name = "recipes")
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "recipe_id")
private Long id;
private String name;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "recipe_id")
private List<Ingredient> ingredients = new ArrayList<>();
}需要注意的是,复合键不能具有空值。因此,只有当你知道每一种成分都与食谱有关时,这才有意义。见这个答案在StackOverflow上和这个冬眠的Jira
有关更多细节,您可以查看Hibernate ORM文档。
https://stackoverflow.com/questions/66819015
复制相似问题