Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring DATA JPA how to write a method which use contant value for a field to fetch data

Hi I am using Spring Data JPA and want to use feature generate query from method name. I have a field active in DB which have only value 0 and 1. I want to fetch all data with which have active value is 1. This is a constant value so i don't want to pass this value as method arguments.

please suggest what will be the method for the same.

example:

I have a entity 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 */       
}

This is the repository for where I want to write method which will fetch all data for which active is 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*/
}

I am stuck for constant vale please suggest

Thanks Sudhanshu

like image 734
sudhanshu Gupta Avatar asked Jul 25 '17 09:07

sudhanshu Gupta


2 Answers

If you could change that Integer to a boolean, you could be doing something like:

In your entity:

private Boolean                 active;

In your repo:

List<EmailRef> findByActiveIsTrue();
like image 129
kimy82 Avatar answered Nov 20 '22 21:11

kimy82


Try this:

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);
}
like image 36
Cepr0 Avatar answered Nov 20 '22 22:11

Cepr0