首页 > 解决方案 > 如何使用 Spring Data / JPQL 从子类实体属性中进行选择?

问题描述

我需要查询子类的属性。以下是涉及的实体:

@Entity
@Data
public class Course {

    @Id
    private Long id;
    
    @ManyToOne
    @JoinColumn(name = "personId")
    private Person person;

}

@Entity
@Data
@Inheritance(strategy = InheritanceType.JOINED)
public class Person {

    @Id
    private Long id;

    private String name;

}

@Entity
@Data
@EqualsAndHashCode(callSuper=true)
public class Student extends Person {

    @ManyToOne
    @JoinColumn(name="studentTypeId")
    private StudentType studentType;
            
}

@Entity
@Data
public class StudentType {

    @Id
    private Long id;
    
    @Convert(converter = StudentTypeConverter.class)
    private StudentTypeEnum name;
    
    @RequiredArgsConstructor
    @Getter
    @ToString
    public static enum StudentTypeEnum {
        GRADUATE("Graduate");
        
        private final String name;
        
    }

}

我正在尝试使用 Spring Data 存储库进行查询:

public interface CourseRepository extends Repository<Course>  {
    
    List<Course> findByCoursePersonStudentTypeName(@Param("studentTypeName") String studentTypeName);
}

但这不起作用。它会生成一个错误声明No property StudentTypeName found for Person!。这是有道理的,因为该属性仅存在于Student.

如何编写此方法(最好)或使用 JPQL 按学生类型查找课程?

标签: hibernatejpaspring-data-jpaspring-datajpql

解决方案


尝试这个

@Query("select c from Course c join c.person as p, Student s where p.id = s.id and s.studentType.name = ?1")
List<Course> findByCoursePersonStudentTypeName(StudentTypeEnum studentTypeEnum);

推荐阅读