【问题标题】:@MappedSuperclass and implementation table@MappedSuperclass 和实现表
【发布时间】:2017-03-27 23:27:36
【问题描述】:

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

我正在重构代码,并认为最好将我们当前的实体分解,以便 Report 是具有 type 实现的抽象类。例如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(){
      ...
   }
}

【问题讨论】:

  • 看看this,它应该已经涵盖了您的问题。
  • @AlexanderBischof - 我没有看到任何将多个具体实现保存到同一张表的示例。

标签: java jpa inheritance mappedsuperclass


【解决方案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,因为它已经用于创建所需的实体。

这就是你要找的吗?

【讨论】:

  • 是的。完美的。谢谢!
猜你喜欢
  • 2015-02-17
  • 1970-01-01
  • 2011-06-13
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 2015-04-16
  • 1970-01-01
相关资源
最近更新 更多