gpt4 book ai didi

jpa - 如何使用 JPA 创建这种多对一映射?

转载 作者:行者123 更新时间:2023-12-04 18:35:21 27 4
gpt4 key购买 nike

我想实现以下架构:

Table A:
a_id
(other columns)



Table B:
b_id
(other columns)



Table C:
c_id
(other columns)



Table D:
a_id_fk
b_id_fk
c_id_fk



我想知道如何创建实体 D。所有键 a_id_fk , b_id_fkc_id_fk在表 D 中形成一个复合主键。

谢谢

最佳答案

它模拟了一个三元关联。为了使用它,您需要一张 map 。 JPA 1.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>();

}

请注意,每个键都是 B,每个值都是 C 实体。在实践中,它通过 B 实体绑定(bind) A 和 C。
@Entity
public class B {

@Id
private Integer id;

}

@Entity
public class C {

@Id
private Integer id;

}

或者,如果您不想要 map ,您可以根据以下方式对实体 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
}

}

}

问候,

关于jpa - 如何使用 JPA 创建这种多对一映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1460547/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com