我需要你的帮助来映射两个表的Hibernate中的关系 @ElementCollection注释。
第一个是父表
表名:父
数据库列
KEY1 Char (first primary key field)
KEY2 Char (second primary key field)
DESCRIPTION Char
DEPENDENTID BigInt
第二个是依赖表
TableName:依赖
数据库列
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
}
然后我创造了两个豆子:
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:依赖 [iDependentBeans_PARENTID,iDependentBeans_CODE]))必须具有相同的功能 列数作为引用的主键(DEPENDENT [PARENTID,iDependentBeans_PARENTID,iDependentBeans_CODE])
所以我做错了什么,但我无法想象。 有人可以帮我吗?
答案 0 :(得分:7)
@ElementCollection应与基本类型或可嵌入类一起使用,而不是与实体一起使用。
DependentBean是一个实体。
尝试使用一对多映射并修改架构
PARENT架构
KEY1 Char (PK)
KEY2 Char (PK)
DEPENDENTID BigInt (PK)
DESCRIPTION Char
DEPENDENT架构
CODE Char (PK)
PARENTID BigInt (FK)
KEY1 Char (FK)
KEY2 Char (FK)
FIELD1 Char
FIELD2 Char
一对多映射
ParentPK
@Embeddable
public class ParentPK {
@Column(name = "K1")
private String iK1;
@Column(name = "K2")
private String iK2;
@Column(name = "DEPENDENTID")
private long iDependentId;
}
ParentBean
@Entity
@Table(name = "PARENT")
public class ParentBean {
@EmbeddedId
ParentPK iParentPK;
@OneToMany(mappedBy = "parent")
List<DependentBean> iDependentBeans;
}
DependentBean
@Entity
@Table(name = "DEPENDENT")
public class DependentBean {
@Id
@Column(name = "CODE")
private String iCode;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "PARENTID", referencedColumnName = "iDependentId"),
@JoinColumn(name = "K1", referencedColumnName = "iK1"),
@JoinColumn(name = "K2", referencedColumnName = "iK2") })
ParentBean parent;
}