在集合字段中查找元素Spring Data JPA Query

时间:2018-06-28 14:43:36

标签: java spring jpa spring-data-jpa

我有一个包含收集字段的实体

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

我想返回现场作业包含我的变量“ job”的服务

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

尽管现场作业包含我的变量,它总是返回一个空列表

有任何建议吗?

2 个答案:

答案 0 :(得分:2)

尝试一个自定义查询,您可以在其中使用member of,如下所示:

@Query("SELECT s FROM Service s WHERE ?1 member of s.jobs")
List<Service> findByJobs(String job)

答案 1 :(得分:1)

您可以这样

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

要使其正常工作,您必须像这样更改实体

public class Service {
    @ElementCollection
    private List<String> jobs
}