简体   繁体   中英

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?

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)

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM