SpringDataJPA如何编写一个使用contant值作为字段来获取数据的方法

SpringDataJPA如何编写一个使用contant值作为字段来获取数据的方法,spring,spring-data-jpa,Spring,Spring Data Jpa,您好,我正在使用SpringDataJPA,希望使用FeatureGenerateQueryfromMethodName。我在DB中有一个活动字段,它只有值0和1。我想获取活动值为1的所有数据。 这是一个常量值,所以我不想将此值作为方法参数传递 请建议同样的方法 例如: 我有一个实体EmailRef public class EmailRef { /* other vareialbe */ @Column(name="is_active") /* this is the fi

您好,我正在使用SpringDataJPA,希望使用FeatureGenerateQueryfromMethodName。我在DB中有一个活动字段,它只有值0和1。我想获取活动值为1的所有数据。 这是一个常量值,所以我不想将此值作为方法参数传递

请建议同样的方法

例如:

我有一个实体EmailRef

public class EmailRef {

    /* other vareialbe */

    @Column(name="is_active") /* this is the field which value is 0 and 1 in DB*/
    private Integer active;

    /* setter getter method */       
}
这是我想要为其编写方法的存储库,该方法将获取活动为1的所有数据

public interface EmailRefRepositry extends JpaRepository<EmailRef, Long> {          

    @Query("select * from email_reference where is_active=1") /* this is the query I want to convert into method*/
    List<EmailRef> findByActive(); /*I want to write method like that which will fetch all data form table where active field value is 1*/
}
我被困在恒谷,请建议

谢谢
Sudhanshu

如果您可以将该整数更改为布尔值,您可以执行以下操作:

在您的实体中:

private Boolean                 active;
在回购协议中:

List<EmailRef> findByActiveIsTrue();
试试这个:

public interface EmailRefRepositry extends JpaRepository<EmailRef, Long> {          

    @Query("select e from EmailRef e where e.active=1")
    List<EmailRef> findOnlyActiveWithQuery();

    default List<EmailRef> findOnlyActive() {
        findByActive(1);
    }

    default List<EmailRef> findNotActive() {
        findByActive(0);
    }

    List<EmailRef> findByActive(Integer active);
}

我不认为您可以使用Spring JPAs magic做您想做的事情,因为它从方法名派生查询,除非您能够按照@kimy82在其解决方案中建议的那样做。当然,您可以在存储库方法上使用@Query注释。但是,您定义的查询不起作用,因为它是本机查询,并且您没有指定该查询。以下是对查询注释的两种可能的修复方法,但我推荐第一种:

@Query("select e from EmailRef e where e.active=1")


如果您的查询有什么问题?FindByaActiviesTrue将完成此任务
@Query("select * from email_reference where is_active=1", nativeQuery=true)