Spring JPA Hibernate如何查找数组列包含某些元素的命名查询

Spring JPA Hibernate how to find array column contains certain elements Named Query

假设我有一个实体

@Entity
public class Course{
    @Id
    private Long id;

    private String courseName;

    //getter and setters
}

现在我想通过它的 name 找到一个 Course,因此在它的存储库中,我放置了一个命名查询,

public interface CourseRepository extends JpaRepository<Course, Long> {

    @Query(value = "SELECT * FROM course c where c.name = :name", nativeQuery=true)
    List<Course> findByName(@Param("name") String name);

}

现在假设 Course 实体获得一个 String[] 列,其中将包含课程 class 应该举行的天数的名称。所以实体变成

@Entity
public class Course{
    @Id
    private Long id;

    private String courseName;

    //will contain {"Tue", "Wed", "Thr"} etc ... the class days
    private String [] classDays; 

    //getter and setters
}

现在我想查找 Thr. 举办的课程,我该如何为此编写命名查询?我有这样的想法

SELECT * FROM course c where :day in c.class_days

但这行得通吗?

不,因为 classDays 未映射为以这种方式工作(它将像 bytea(postgresql) 或 blob(oracle) 一样传递到数据库,而不是字符串列表)。您可以使用 @ElementCollection 来执行此查询 SELECT * FROM course c where :day in c.class_days

@Entity
public class Course{
    @Id
    private Long id;

    private String courseName;

    //will contain {"Tue", "Wed", "Thr"} etc ... the class days
    @ElementCollection
    @CollectionTable(
        name="class_days_table",
        joinColumns=@JoinColumn(name="COURSE_ID")
  )
  @Column(name="class_days")
    private List<String> classDays; 

    //getter and setters
}