hibernatejpaspring-data-jpaspring-datajpql

How to select from subclass entity property using Spring Data / JPQL?


I need to query on a property of a subclass. Here are the entities involved:

@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;
        
    }

}

I'm trying to query using a Spring Data repository:

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

This doesn't work though. It generates an error stating No property StudentTypeName found for Person!. This makes sense since the property exists only on Student.

How can I write this method (preferably) or use JPQL to find the courses by type of student?


Solution

  • How about this:

    @Query("select c from Course c join c.person as p where UPPER(p.studentType.name) = UPPER(?1)")
    List<Course> findByCoursePersonStudentTypeName(String studentTypeName);
    

    This uses a feature of Hibernate called implict casting.