我是JPA的新手,我试图映射旧数据库。文件可以单独正确加载,但关系无法正常工作。任何帮助,将不胜感激。帮助在JPA 2.0中映射复合外键
的Java
@Entity
@IdClass(ParentKey.class)
public class Parent {
@Id
@Column(name="code")
private String code;
@Id
@Column(name="id")
private int id;
@OneToMany(mappedBy="parent")
private List<Child> children = new ArrayList<Child>();
}
public class ParentKey {
private String code;
private int id;
}
@Entity
@IdClass(ChildKey.class)
public class Child {
@Id
@JoinColumns({
@JoinColumn(name="code")
@JoinColumn(name="id")
})
private Parent parent;
@Id
@Column(name="index")
private int index;
}
public class ChildKey {
private String code;
private int id;
private int index;
}
SQL
create table Parent(
code char(4) not null,
id int not null,
primary key(code,id)
);
create table Child(
code char(4) not null,
id int not null,
index int not null,
primary key(code, id, index),
foreign key(code, id) references Parent(code,id)
);
编辑1: 添加ChildKey和ParentKey类。
我忘记了@IdClass添加到我的例子中,第一时间,但现在已经纠正。感谢您的链接,但它没有包含外键的主键示例。我需要一个更复杂的例子来代表上面例子中给出的关系。 – 2011-04-19 19:55:17
是的。 Address.PK拥有帐户作为其PK的一部分。您的ChildKey不正确 – DataNucleus 2011-04-20 07:48:17
您是对的;当我通读它时我没有看到它。我结束了使用OpenJPA的反向映射工具,它给了我解决方案。谢谢你的帮助。 – 2011-04-20 12:06:01