JPA实体继承

时间:2018-08-16 07:52:01

标签: jpa eclipselink

假设我有这个课程:

@Entity
public class VehicleReport {
    @Id
    @GeneratedValue
    private Long id;

    @Column
    @Enumerated(ORDINAL)
    private VehicleType vehicleType;

    @OneToMany?
    private Collection<Vehicle> vehicles;
}

我希望每种车辆类型都有其自己的子表,其中包含每种车辆类型所需的信息。 例如:

抽象类为Vehicle

@Entity
public abstract class Vehicle {
    @ManyToOne
    public VehicleReport report;

}

每种车辆的具体类别

@Entity
public class Car extends Vehicle {
    //Specific "Car" columns
}

如何在父类VehicleReport中进行联接以获取依赖于VehicleTypeVehicleReport的正确子项?

我已经读过@DiscriminatorColumn,但这是否意味着我也将VehicleType保存在我的所有子表中?即使他们有指向父VehicleReport的FK吗?

寻求所有帮助

2 个答案:

答案 0 :(得分:1)

我认为这对您有用。 首先,您需要为@Inheritance类添加Vehicle注释。

然后定义一个@DiscriminatorColumnVehicle

@DiscriminatorValue定义为Car类。像这样:

@Entity
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
@DiscriminatorValue("DISC_VEHICLE")
public class Vehicle {
    @ManyToOne
    public VehicleReport report;
}

@Entity
@DiscriminatorValue("DISC_CAR")
public class Car extends Vehicle {
    //Specific "Car" columns
}

当继承策略为@Discriminator...且您想指定与继承相关的列时,可以使用strategy=SINGLE_TABLE批注。当继承策略为InheritanceType.TABLE_PER_CLASS时,这些注释毫无意义。但是只有使用@Inheritance,您的代码才能作为@Veselin Davidow的答案。因为默认策略是strategy=SINGLE_TABLE

答案 1 :(得分:0)

您可以使用继承策略创建实体

   @Entity
   @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
   public abstract class Vehicle {
        @ManyToOne
        public VehicleReport report;

   }

  @Entity
  public class Car extends Vehicle {
    //Specific "Car" columns
  }

在报告类中

@OneToMany
private Collection<Vehicle> vehicles;

将按预期工作-收集不同级别的车辆。您甚至可以执行“选择所有车辆”(无需选择该关系),它应该可以正常工作。

您可以查看一个不错的博客here和更多信息here

相关问题