如何使用JPA创建多对一映射?
我希望实现以下模式: 表A:如何使用JPA创建多对一映射?,jpa,Jpa,我希望实现以下模式: 表A: a\u id (其他栏目) 表B: b_id (其他栏目) 表C: c\u id (其他栏目) 表D: a\u id\u fk b\u id\u fk c\u id\u fk 我想知道如何创建实体D。表D中的所有键a_id_fk、b_id_fk和c_id_fk构成一个复合主键 谢谢它模拟了三元关联。为了使用它,你需要一张地图。JPA1.0不支持Map,所以如果您想使用它,您需要Hibernate,因为它的Map支持。有点像 @Entity public cla
a\u id
(其他栏目)
表B:
b_id
(其他栏目)
表C:
c\u id
(其他栏目)
表D:
a\u id\u fk
b\u id\u fk
c\u id\u fk
我想知道如何创建实体D。表D中的所有键a_id_fk
、b_id_fk
和c_id_fk
构成一个复合主键
谢谢它模拟了三元关联。为了使用它,你需要一张地图。JPA1.0不支持Map,所以如果您想使用它,您需要Hibernate,因为它的Map支持。有点像
@Entity
public class A {
@ManyToMany
@org.hibernate.annotations.MapKeyManyToMany(
joinColumns=@JoinColumn(name="B_ID")
)
@JoinTable(
name="D",
joinColumns=@JoinColumn(name="A_ID"),
inverseJoinColumns=@JoinColumn(name="C_ID")
)
private Map<B, C> bAndC = new HashMap<B, C>();
}
或者,如果不需要地图,可以根据ABC对实体建模
public class AbC {
@ManyToOne
@JoinColumn(name="A_ID", insertable=false, updateable=false)
private A a;
@ManyToOne
@JoinColumn(name="B_ID", insertable=false, updateable=false)
private B b;
@ManyToOne
@JoinColumn(name="C_ID", insertable=false, updateable=false)
private C c;
@EmbeddedId
private A_b_C_i_D id;
@Embeddable
public static class A_b_C_i_D implements Serializable {
@Column(name="A_ID", updateable=false)
private Integer a_i_d;
@Column(name="B_ID", updateable=false)
private Integer b_i_d;
@Column(name="C_ID", updateable=false)
private Integer c_i_d;
// getter's and setter's
public boolean equals(Object o) {
if(o == null)
return false;
if(!(o instanceof A_b_C_i_D))
return false;
A_b_C_i_D other = (A_b_C_i_D) o;
if(!(getA_i_d().equals(other.getA_i_d()))
return false;
if(!(getB_i_d().equals(other.getB_i_d()))
return false;
if(!(getC_i_d().equals(other.getC_i_d()))
return false;
return true;
}
public int hashcode() {
// hashcode implementation
}
}
}
问候,谢谢。非常具有描述性和帮助性
public class AbC {
@ManyToOne
@JoinColumn(name="A_ID", insertable=false, updateable=false)
private A a;
@ManyToOne
@JoinColumn(name="B_ID", insertable=false, updateable=false)
private B b;
@ManyToOne
@JoinColumn(name="C_ID", insertable=false, updateable=false)
private C c;
@EmbeddedId
private A_b_C_i_D id;
@Embeddable
public static class A_b_C_i_D implements Serializable {
@Column(name="A_ID", updateable=false)
private Integer a_i_d;
@Column(name="B_ID", updateable=false)
private Integer b_i_d;
@Column(name="C_ID", updateable=false)
private Integer c_i_d;
// getter's and setter's
public boolean equals(Object o) {
if(o == null)
return false;
if(!(o instanceof A_b_C_i_D))
return false;
A_b_C_i_D other = (A_b_C_i_D) o;
if(!(getA_i_d().equals(other.getA_i_d()))
return false;
if(!(getB_i_d().equals(other.getB_i_d()))
return false;
if(!(getC_i_d().equals(other.getC_i_d()))
return false;
return true;
}
public int hashcode() {
// hashcode implementation
}
}
}