使用鉴别器值查询数据库

Query the database using discriminator values

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

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

这是我的parentclass

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

这是两个 child 实体

@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
}

我想通过分别筛选年假和休假来查询数据库。这意味着当我搜索年假时,应该检索鉴别器列中值为 "annual" 的所有记录。我该如何实施。 提前致谢!

为 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); 

}

CausalLeaveRepo.java

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

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

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

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

您不必明确过滤掉。

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