我在JPA中对以下问题进行建模时遇到问题。我有一个JPA实体类'User',如下所示: (为了简洁起见,省略了访问器/ mutators /无关字段/无关的JPA配置)
@Entity
class User {
@Id
@Generated Value
long id;
@OneToMany
Report contributorReports; // All the reports where this user is contributor
@OneToMany ownerReports; // All the reports where this user is owner
String username;
}
和JPA实体类'报告'
@Entity
class Report {
@Id
@GeneratedValue
long id;
@OneToOne
User contributor;
@OneToOne
User owner;
SomeData data;
}
我想建立一种关系:
我想我最终会得到一张看起来模糊不清的映射表:
CREATE TABLE user_report {
BIGINT reportId,
BIGINT contributorId,
BIGINT ownerId,
}
我试图解决问题,如:
@OneToOne
@JoinTable(name = "user_report",
joinColumns = {
@JoinColumn(name = "reportOwner_ID", referencedColumnName = "ID")}
)
private User owner;
@OneToOne
@JoinTable(name = "user_report",
joinColumns = {
@JoinColumn(name = "reportContributor_ID", referencedColumnName = "ID")}
)
private User contributor;
这会生成一个表格,如:
CREATE TABLE user_report (
BIGINT ownerReport_ID, // Report ID
BIGINT reportOwner_ID, // UserID owner
BIGINT contributorReport_ID, // Report ID
BIGINT reportContributor_ID // UserID contributor
)
因此,当JPA尝试映射到此表时,它会单独映射每个字段并失败,因为只有一半的行被提交,抛出此异常:
Caused by: java.sql.BatchUpdateException: Field 'ownerReport_ID' doesn't have a default value
我希望能够就如何最好地建立我想象的关系建立一些方向。 (或者可能是设想这种关系的更好方式)如果需要其他信息,我很乐意提供。
亲切的问候 马特
答案 0 :(得分:2)
根据您的要求,我相信您可以通过2 1:M从用户到报告完成此操作,每个匹配的M:1返回。
@Entity
class User {
@Id
@Generated Value
long id;
// All the reports where this user is contributor
@OneToMany(mappedBy="contributor")
List<Report> contributorReports;
// All the reports where this user is owner
@OneToMany(mappedBy="owner")
List<Report> ownerReports;
String username;
}
然后您的报告类看起来像:
@Entity
class Report {
@Id
@GeneratedValue
long id;
@ManyToOne
User contributor;
@ManyToOne
User owner;
SomeData data;
}
这种情况也可以通过连接表进行,但根据您的要求不需要,因为我理解它们。
道格