hibernate - 如何使用 Spring Data/JPQL 从子类实体属性中进行选择?

标签 hibernate jpa spring-data-jpa 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 数据存储库进行查询:

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/

相关文章:

java - JPA Criteria Builder 按总和列排序

java - Hibernate 关系获取配置文件

hibernate - 如何在 NetBeans 中包含 Hibernate Javadoc?

java - 如何解决自定义存储库 JPA 中的错误 "error in your SQL syntax"

java - 使用输入列表获取实体对象列表 : Spring Data JPA - Hibernate

java - Spring Data 与 Spring Data JPA 与 JdbcTemplate

java - 如何使用 spring data jpa 仅更新模型中的传入字段?

java - java、hibernate.initialize() 的奇怪行为

spring - 为什么还要为 DAO 层烦恼

java - 在 JPA 中使用 LocalDateTime 和 @Version 注释