我有三张桌子
CREATE TABLE "ingredient" (
"id" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY,
"ingredient" VARCHAR(50) NOT NULL
);
CREATE TABLE "pizza" (
"id" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY,
"pizza" VARCHAR(50) NOT NULL
);
CREATE TABLE "pizza_structure" (
"pizza_id" INT NOT NULL,
"ingredient_id" INT NOT NULL,
"amount" INT NOT NULL
);
如何加入它们,将Pizzas结构作为Map
@Entity
@Table(name = "ingredient")
public class Ingredient{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Ingredient() {
}
}
@Entity
@Table(name = "pizza")
public class Pizza {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany ????
private Map<Ingredient, Integer> pizzaStructure;
public Pizza() {
}
public Pizza(String name, Map<Long, Integer> pizzaStructure) {
this.name = name;
this.pizzaStructure = pizzaStructure;
}
}
我是否需要创建@Embeddable类PizzaStructure,如果是,如何使用它?
现在我收到了一个错误 调用init方法失败;嵌套异常是org.hibernate.AnnotationException:使用@OneToMany或@ManyToMany定位未映射的类:
答案 0 :(得分:0)
如何加入它们,将Pizzas结构作为Map
看起来像这样:
@ElementCollection
@CollectionTable(name = "pizza_structure", joinColumns = {@JoinColumn(name = "pizza_id")})
@Column(name = "amount")
@MapKeyJoinColumn(name = "ingredient_id")
private Map<Ingredient, Integer> pizzaStructure;
我是否需要创建@Embeddable类PizzaStructure
没有
更多信息在这里:Hibernate User Guide - Maps。
请注意,表格pizza_structure
应包含pizza
和ingredient
表的外键以及pizza_id
和ingredient_id
的唯一约束,如下所示(&# 39; postgresql方言):
create table pizza_structure
(
pizza_id ... constraint fk_structure_pizza references pizza,
ingredient_id ... constraint fk_structure_ingredient references ingredient,
amount ...,
constraint pizza_structure_pkey primary key (pizza_id, ingredient_id)
);