Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find elements in a collection field Spring Data JPA Query

I have an entity contains a collection field

@Entity
@Table(name = "SERVICE")
    public class Service {

@Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQUENCE")
    @SequenceGenerator(name = "SEQUENCE", sequenceName = "SEQUENCE")
    @Column(name = "ID_SERVICE")
    private Integer id;

        @ElementCollection
    @CollectionTable(name = "SERVICE_JOB",
            joinColumns = @JoinColumn(name = "ID_SERVICE", referencedColumnName = "ID_SERVICE"))
    @Column(name = "JOB")
    private List<String> jobs = new ArrayList<String>();
    }

I want to return services where field jobs contains my variable "job"

@Query("SELECT DISTINCT s FROM Service s WHERE ?1 in (s.jobs)")
List<Service> findByJob(String job);

It always returns an empty list although field jobs contains my variable

Any suggesstions?

like image 838
Ghizlane Lotfi Avatar asked Jun 28 '18 14:06

Ghizlane Lotfi


People also ask

How to create finder methods in data JPA?

Behind the scenes, Data JPA will create SQL queries based on the finder method and execute the query for us. To create finder methods in Data JPA, we need to follow a certain naming convention. To create finder methods for the entity class field name, we need to create a method starting with findBy followed by field name.

How to use JPA with spring data JPA?

One initial approach is of course to use the built in Spring Data JPA support for searching based on declaring methods in your repository. Let’s say we want to find all employees based on their birthDate we can easily do that by declaring a query in our JPA repository interface.

How to query the database using data JPA?

To query the database that should match both name and location then we need to create a method like this – To query the database that should match any one of the columns then we need to create a method like this – Behind the scenes, Data JPA will create a SQL query like this –

How do I use @query in spring?

Select Query In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.


2 Answers

try a custom query where you can use member of like so :

@Query("SELECT s FROM Service s WHERE ?1 member of s.jobs")
List<Service> findByJobs(String job)
like image 76
YCF_L Avatar answered Nov 14 '22 20:11

YCF_L


You can do it this way

@Query("select s from Service s WHERE :job in elements(s.jobs)")
List<Service> getAllByJobs(@Param("job") String job)

For this to work you have to change your Entity a bit, like this

public class Service {
    @ElementCollection
    private List<String> jobs
}
like image 22
pvpkiran Avatar answered Nov 14 '22 20:11

pvpkiran