使用鉴别器值查询数据库

m-2*_*127 5 inheritance hibernate single-table-inheritance spring-data-jpa spring-boot

我正在使用单表继承策略。我想通过使用鉴别器类型过滤数据库来在数据库中执行搜索。我如何在 JPA 中编写一个函数来执行此操作。

使用 method 定义方法的正常方式findBy...不会产生结果。

这是我的家长课

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
        name="Leave_Type",
        discriminatorType=DiscriminatorType.STRING
        )
public class LeaveQuota {
// the fields and the required methods
}
Run Code Online (Sandbox Code Playgroud)

这是两个子实体

@Entity
@DiscriminatorValue("Annual")
public class AnnualLeave extends LeaveQuota {
// the fields and the required methods
}

@Entity
@DiscriminatorValue("Casual")
public class CasualLeave extends LeaveQuota {
// the fields and the required methods
}
Run Code Online (Sandbox Code Playgroud)

我想通过分别过滤年假和休闲假来查询数据库。这意味着当我搜索年假时,应检索鉴别器列中值为“annual”的所有记录。我怎样才能实现这个。提前致谢!

Joy*_*Joy 7

为 AnnualLeave.java 创建存储库,即 AnnualLeaveRepo.java 和 CausualLeave.java,如下所示:

AnnualLeaveRepo.java

@Repository
public interface AnnualLeaveRepo extends JpaRepository<AnnualLeave,Integer>   {

    @Query("from AnnualLeave")
    public List<AnnualLeave> getLeaves();

    //consider noOfLeave is member of AnnualLeave.java class
    public List<AnnualLeave> findByNoOfLeave(int noOfLeave); 

}
Run Code Online (Sandbox Code Playgroud)

CausalLeaveRepo.java

@Repository
public interface CausalLeaveRepo extends JpaRepository<CausalLeave,Integer>   {

    @Query("from CausalLeave")
    public List<CausalLeave> getLeaves();
}
Run Code Online (Sandbox Code Playgroud)

现在,当您使用findAll()getLeaves()findByNoOfLeave(int)方法或AnnualLeaveRepo类的任何其他自定义抽象方法时,它将自动使用Leave_Type="Annual"过滤结果。

类似地,当您使用findAll()getLeaves()方法或CausalLeaveRepo类的任何其他自定义抽象方法时,它将自动使用Leave_Type="Causal"过滤结果。

您不必明确过滤掉。

注意 如果您的类中有任何属性与 LeaveQuota 实体或其继承实体有关系(@OneToMany 等),那么不要忘记在这些属性上使用 @JsonIgnore 注释。否则你会得到一个 stackoverflow 错误