@MappedSuperclass和实现表

时间:2017-03-27 23:27:37

标签: java jpa inheritance mappedsuperclass

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

我正在重构代码并认为最好打破我们当前的实体,以便Report是一个带有type实现的抽象类。例如DmvReport extends ReportCreditScoreReport extends Report

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

以下是我继承的错误代码的示例

报告课

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

CreditReport类

@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(){
      ...
   }
}

1 个答案:

答案 0 :(得分:0)

我认为您应该使用@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,因为它已用于创建所需的实体。

这是你正在寻找的吗?