gpt4 book ai didi

java - JPA 映射问题 - 请求建模方向

转载 作者:行者123 更新时间:2023-12-02 08:30:44 25 4
gpt4 key购买 nike

我在 JPA 中对以下问题进行建模时遇到问题。我有一个 JPA 实体类“User”,如下所示:(为简洁起见,省略了访问器/修改器/无关字段/无关 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 实体类“Report”


@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 尝试映射到该表时,它会单独映射每个字段并失败,因为只有一半的行被提交,并抛出此异常:


原因:java.sql.BatchUpdateException:字段“ownerReport_ID”没有默认值

我希望就如何最好地构建我设想的关系获得一些指导。 (或者也许是设想这种关系的更好方式)如果需要其他信息,我很乐意提供。

亲切的问候马特

最佳答案

根据您的要求,我相信您可以通过从用户到报告的 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;
}

那么您的 Report 类将如下所示:

@Entity
class Report {
@Id
@GeneratedValue
long id;

@ManyToOne
User contributor;

@ManyToOne
User owner;

SomeData data;
}

使用连接表也可能出现这种情况,但据我了解,根据您的要求,这不是必需的。

道格

关于java - JPA 映射问题 - 请求建模方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3441433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com