sudhanshu Gupta
sudhanshu Gupta

Reputation: 71

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

Upvotes: 7

Views: 6407

Answers (3)

Plog
Plog

Reputation: 9622

I don't think you can do what you want using Spring JPAs magic where is derives the query from the method name (unless you are able to do as @kimy82 suggests in their solution). You can of course use the @Query annotation on your repository method though. However the one you have defined won't work because it is a native query and you have no specified that. Here are two possible fixes to your Query annotation although I would recommend the first:

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

or

@Query("select * from email_reference where is_active=1", nativeQuery=true)

Upvotes: 0

Cepr0
Cepr0

Reputation: 30309

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

Upvotes: 2

kimy82
kimy82

Reputation: 4475

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

Upvotes: 5

Related Questions