【发布时间】:2010-08-30 05:23:34
【问题描述】:
我无法让这项工作正常进行,我想知道我正在做的事情是否没有意义?
public class Application {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id")
private long id;
....
}
@MappedSuperclass
public abstract class Sample {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToOne (cascade=CascadeType.ALL)
protected Application application;
....
}
// TestSample contains a list that is mapped not by the primary key of the Sample
public class TestSample extends Sample {
@OneToMany(mappedBy="application", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private List<Part> parts = new ArrayList<Part>();
....
}
public class Part {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private long id = 0;
@ManyToOne (cascade=CascadeType.ALL, fetch=FetchType.LAZY)
Application application;
}
我遇到的问题是我能够添加部分,数据库看起来正确,然后当我尝试获取 parts 列表时,我得到一个空列表。
如果我通过更改这些类在数据库结构上妥协,我可以让它工作:
// TestSample contains a list that is mapped not by the primary key of the Sample
public class TestSample extends Sample {
@OneToMany(mappedBy="testSample", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private List<Part> parts = new ArrayList<Part>();
....
}
public class Part {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private long id = 0;
@ManyToOne (cascade=CascadeType.ALL, fetch=FetchType.LAZY)
TestSample testSample;
}
表格是由休眠自动生成的,所以它们是这样出来的:
application
id : number
....
test_sample
id : number
application_id : number
...
part
id : number
application_id : number
如果我将其更改为不太理想的工作方式,最后一张表会有所不同:
part
id : number
test_sample_id : number
因为所有情况下的 id 都是自动生成的,所以没有共享主键。本质上,我想要做的是使用 mappedby,其中 mappedby 指的是一个不是名为“TestSample”的表/类的主键的字段。我不确定这在 JPA 中是否有意义。
【问题讨论】:
-
我不明白您的映射(您的一侧有 OneToOne,另一侧有 OneToMany)。如果不在 PK 上,外键是如何定义的?你能展示你的桌子吗?
-
我已经添加了最后一课,希望这可以清除它。
TestSample有Parts。但是因为TestSample与Application是一对一的关系,所以我在parts列表中使用Application 的主键。 -
OneToMany来自TestSample不是双向的,为什么它有一个mappedBy?另外,请显示表格和约束,我想了解这应该如何工作(您是否在Application和Sample之间使用共享主键?) -
OneToMany 与“Part”类是双向的。我认为这很难解释(: