Rajendra
Rajendra

Reputation: 89

Jpa query with distinct and not null

How to write jpa query with distinct and not null in spring boot? Below is the example.

Employee Entity Class sql query is:

select distinct job from emp where job is not null

How to write above query in jpa.

I have tried findByJobNotNull() here null is working fine but need to distinct how to do it please suggest.

enter image description here

Upvotes: 1

Views: 2650

Answers (2)

SternK
SternK

Reputation: 13041

  1. You can use the following query:
@Query("select distinct e.job from Employee e where e.job is not null")
List<String> findJobs();
  1. You can use projections.

Assuming that you have:

@Entity
class Employee {
   // ...

   @Column(name = "job")
   public String getJob()
   {
      return job;
   }
}

You can create an interface-based projection:

public interface EmployeeJob
{
   String getJob();
}

and then add the following method to your Employee repository:

List<EmployeeJob> findDistinctByJobNotNull();

You can find additional information in the documentation.

Upvotes: 1

mahfuj asif
mahfuj asif

Reputation: 1979

Just need to add Distinct to the method name

findDistinctByJobNotNull()

Upvotes: 2

Related Questions