帮助在JPA 2.0中映射复合外键 [英] Help Mapping a Composite Foreign Key in JPA 2.0
本文介绍了帮助在JPA 2.0中映射复合外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是JPA的新手,我正在尝试映射旧数据库.文件分别正确加载,但关系无法正常运行.任何帮助将不胜感激.
I'm new to JPA and I'm trying to map a legacy database. The files load correctly individually but the relationships are not working correctly. Any help would be appreciated.
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)
);
添加ChildKey和ParentKey类.
edit 1: add the ChildKey and ParentKey classes.
推荐答案
这是OpenJPA使用其反向映射工具创建的文件,它似乎工作正常.
Here is what OpenJPA created using its ReverseMapping Tool and it appears to be working correctly.
@Entity
@Table(name="PARENT")
@IdClass(ParentId.class)
public class Parent {
@OneToMany(targetEntity=Child.class, mappedBy="parent", cascade=CascadeType.MERGE)
private Set childs = new HashSet();
@Id
@Column(length=4)
private String code;
@Id
private int id;
//omitted getters, setters
}
public class ParentId implements Serializable {
public String code;
public int id;
//omitted getters, setters, toString, equals, hashcode
}
@Entity
@Table(name="CHILD")
@IdClass(ChildId.class)
public class Child {
@Id
@Column(length=4)
private String code;
@Id
private int id;
@Id
private int index;
@ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.MERGE)
@JoinColumns({@JoinColumn(name="code"), @JoinColumn(name="id")})
private Parent parent;
//omitted getters, setters
}
public class ChildId implements Serializable {
public String code;
public int id;
public int index;
//omitted getters, setters, toString, equals, hashcode
}
这篇关于帮助在JPA 2.0中映射复合外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文