hibernate - 如何使用 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 按学生类型查找课程?
解决方案
尝试这个
@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);
推荐阅读
- android - 如何存储 Google ARCore 锚点的位置?
- android - 视图未占用全宽 - ConstraintLayout - RecyclerView - Android
- javascript - 如何将传递函数作为道具发送给子组件
- python - Discord.py 加载 json 数据
- image - 在 Flutter 中使旋转后的图像适合屏幕
- sql - 所有列上的like子句
- amazon-web-services - NGNIX redirect_uri 与 AWS Cognito
- r - R中行的条件切片
- angular - Angular Firebase 应用程序成功托管在 Google Cloud Platform 中。但是该网站给出了错误
- postgresql - 无法通过主机名连接到 RDS