1

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

我正在重构代码,并认为最好将我们当前的实体分解,这样它Report就是一个具有type实现的抽象类。例如 a DmvReport extends ReportCreditScoreReport extends 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(){
      ...
   }
}
4

1 回答 1

1

我认为你应该使用@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) 中,但根据report_value_id字段实例化适当的实体。您不必report_value_id在参数中定义 ,因为它已用于创建所需的实体。

这是你要找的吗?

于 2017-09-28T20:05:25.987 回答