首页 > 解决方案 > 使用 JpaRepository 过滤子类单表的子类实体

问题描述

我有一个名为 Vehicle 的子类,它是抽象的,并由两个子类 Car 和 Motorbike 扩展。

在 DAO 层上,我只为 Vehicle单表创建了一个接口存储库,其中包括所有车辆类型(汽车和摩托车),在这个存储库接口中,我需要创建一个方法 findCars,它只返回主表 Vehicle 中的 Car 实体,并且另一种方法 findMotorbikes 返回 Motorbike 实体,请问我该如何操作。

这是 Vehicle 类的代码:

@Entity
@Table(name = "Vehicle")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "Type", discriminatorType = DiscriminatorType.STRING, length = 10)
public abstract class Vehicle {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String model;
}

车类:

@Entity
@DiscriminatorValue("Car")
public class Car extends Vehicle {
    private String x;
}

摩托车类:

@Entity
@DiscriminatorValue("Motorbike")
public class Motorbike extends Vehicle {
    private String y;
}

标签: javahibernatespring-bootjpaspring-data-jpa

解决方案


推荐阅读