我需要查询子类的属性。以下是涉及的实体:
@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 数据存储库进行查询:
public interface CourseRepository extends Repository<Course> {
List<Course> findByCoursePersonStudentTypeName(@Param("studentTypeName") String studentTypeName);
}
但这不起作用。它会生成一条错误,指出No property StudentTypeName found for Person!
。这是有道理的,因为该属性仅存在于 Student
上。
我如何编写此方法(最好)或使用 JPQL 按学生类型查找类(class)?
最佳答案
这个怎么样:
@Query("select c from Course c join c.person as p where UPPER(p.studentType.name) = UPPER(?1)")
List<Course> findByCoursePersonStudentTypeName(String studentTypeName);
这使用了 Hibernate 的一项称为隐式转换的功能。
关于hibernate - 如何使用 Spring Data/JPQL 从子类实体属性中进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67990054/