【问题标题】:Ignoring a @MappedSuperclass for not extended class JPA忽略未扩展类 JPA 的 @MappedSuperclass
【发布时间】:2019-02-20 06:22:02
【问题描述】:

例如,如果我有两个类 FullTimeEmployeePartTimeEmployeeFullTimeEmployee 必须扩展 Employee 表并使用 @MappedSuperclass 访问该属性,但 PartTimeEmployee 类不需要任何扩展,但如果没有扩展所有其他类,它会抛出 JPA 错误

@MappedSuperclass
public class Employee {
      @Id
      @GeneratedValue
      private long id;
      private String name;
        .............
}

@Entity
public class FullTimeEmployee extends Employee {
  private int salary;
    .............
}

我不想用员工扩展 PartTimeEmployee@MappedSuperclass 不允许我这样做

@Entity
public class PartTimeEmployee {
  private int hourlyRate;
    .............
}

【问题讨论】:

  • 请详细说明。即将发生什么异常以及您想要实现什么。根据您的问题,PartTimeEmployee 是独立实体,可以正常工作。

标签: java hibernate jpa spring-data-jpa persistence


【解决方案1】:

您应该重新考虑您的设计和实体命名。如果您的 PartTimeEmployee 没有扩展 Employee 您至少需要 id 所以:

@Entity
public class PartTimeEmployee {
    @Id
    @GeneratedValue
    private long id;
    private int hourlyRate;
    . . .
}

或者你也可以创建一个更聪明的设计和一个映射的超类,比如:

@MappedSuperclass
public class BaseEntity {
    @Id
    @GeneratedValue
    private long id;

你的Employee 可以扩展它并继承id

@MappedSuperclass
public class Employee extends BaseEntity {
    private String name;
    . . .
}

您的FullTimeEmployee 可以保持原样,PartTimeEmployee 可以扩展BaseEntity 以继承id

@Entity
public class PartTimeEmployee extends BaseEntity {
    private int hourlyRate;
. . .
}

【讨论】:

    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2013-07-04
    • 2017-01-22
    • 1970-01-01
    • 2011-07-19
    • 2012-09-22
    相关资源
    最近更新 更多