我需要您的帮助来使用 @ElementCollection 注释在 Hibernate 中映射两个表的关系。
第一个是父
表表名:Parent
DB Columns
KEY1 Char (first primary key field)
KEY2 Char (second primary key field)
DESCRIPTION Char
DEPENDENTID BigInt
第二个是依赖表
TableName:Dependent
DB Columns
PARENTID BigInt (first primary key field)
CODE Char (second primary key field)
FIELD1 Char
FIELD2 Char
我需要使用 @EmbeddedId 注释为两个表定义 PK,所以我创建了两个类:
@Embeddable
public class ParentPK implements Serializable
{
@Column(name="K1")
private String iK1;
@Column(name="K2")
private String iK2;
// I omit the constructor, getter, setter, equals, hashcode method
}
@Embeddable
public class DependentPK implements Serializable
{
@Column(name="PARENTID")
private String iParentId;
@Column(name="CODE")
private String iCode;
// I omit the constructor, getter, setter, equals, hashcode method
}
然后我创建了两个 bean:
DEPENDENT 表的类。
请注意,在这个类中,我不想有任何关系注释
@Entity
@Table(name = "DEPENDENT")
public class DependentBean implements Serializable
{
@EmbeddedId
private DependentPK iDependentPK;
@Column(name = "FIELD1")
private String iField1;
@Column(name = "FIELD2")
private String iField2;
// I omit the constructor, getter, setter methods
}
以及 PARENT 表的类
@Entity
@Table(name = "PARENT")
public class ParentBean implements Serializable
{
@EmbeddedId
ParentPK iParentPK;
@Column(name = "DESCRIPTION")
private String iDescription;
@Column(name = "DEPENDENTID")
private long iDependentId;
@ElementCollection
@CollectionTable(name="DEPENDENT", joinColumns={@JoinColumn(name="PARENTID", referencedColumnName="DEPENDENTID")})
private Set<DependentBean> iDependentBeans = new HashSet<DependentBean>();
// I omit the constructor, getter, setter methods
}
当我尝试部署时,出现错误:
原因:org.hibernate.MappingException:外键 (FK9619C2A17B05CB2:DEPENDENT [iDependentBeans_PARENTID,iDependentBeans_CODE]) 必须具有与引用的主键相同的列数 (DEPENDENT [PARENTID,iDependentBeans_PARENTID,iDependentBeans_CODE])
所以我做错了什么,但我无法想象是什么。有人愿意帮助我吗?