gpt4 book ai didi

java - @MappedSuperclass和实现表

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:11 24 4
gpt4 key购买 nike

我继承了一些非常糟糕的代码,我希望对其进行重构以使其更可重用。有一组报告表,主要由 3 列组成:idreport_type_fkreport_description。我想将所有报告表合并为一个以便于使用。

我正在重构代码,并认为最好分解我们当前的实体,以便 Report 是一个具有 type 实现的抽象类。例如,DmvReport 扩展了 ReportCreditScoreReport 扩展了 Report 等。

我遇到的问题是,所有实体都需要保存到 1 个报告表。有没有办法将abstract Report对象的所有具体实现保存到同一个表中?

这是我继承的错误代码的示例

报告类

@Entity
@Table(name = "report")
public class Report<E extends Exception> {
private long id;
private ReportType type;
private String description;
...
...
}

信用报告类

@Entity
@Table(name = "credit_report")
public class CreditScore Report<E extends Exception> extends Report<E> {
private long id;
private ReportType type;
private String description;
...
...
}

我希望将其变成:

@MappedSuperclass
@Table(name = "report")
public abstract class Report<E extends Exception> {
@Id @Column(name="id")
private long id;

@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "report_type_id")
private ReportType type;

@column(name="description")
private String description;
...
...
}

@Entity
@Table(name = "report")
public class CreditScoreReport<E extends Exception> extends Report<E> {

public void doCreditScoreStuff(){
...
}
}

@Entity
@Table(name = "report")
public class DmvReport<E extends Exception> extends Report<E> {
public void doDmvStuff(){
...
}
}

最佳答案

我认为你应该使用@Inheritance而不是@MappedSuperClass。您的代码将如下所示:

@Entity
@Table(name = "report")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "report_type_id", discriminatorType = DiscriminatorType.INTEGER)
public abstract class Report<E extends Exception> {
@Id @Column(name="id")
private long id;

@column(name="description")
private String description;
...
...
}

@Entity(name = "CreditScoreReport")
@DiscriminatorValue("1") // the id corresponding to the credit score report
public class CreditScoreReport<E extends Exception> extends Report<E> {

@Column(name = "specific_credit_score_report_1)
private Integer specificCreditScoreReport1;

public void doCreditScoreStuff(){
...
}
}

@Entity(name = "DmvReport")
@DiscriminatorValue("2") // the id corresponding to the DMV report
public class DmvReport<E extends Exception> extends Report<E> {

@Column(name = "specific_dmv_score_report_1)
private Integer specificDmvScoreReport1;

public void doDmvStuff(){
...
}
}

此策略允许您将信用评分报告和 DMV 报告数据存储在一张表(报告)中,但根据 report_value_id 字段实例化正确的实体。您不必在参数中定义 report_value_id,因为它已用于创建所需的实体。

这是您要找的吗?

关于java - @MappedSuperclass和实现表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058105/

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