在 JPA 中是否可以映射具有连接的自定义结果

In JPA is it possible to map custom results which has joins

我有两个实体 StudentAppliedCourses

@Entity
public class Student {
    @Id
    private Long sid;
    private String name;
    private String address;
    .
    .
    .
    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "sid", referencedColumnName = "sid")
    private Set<AppliedCourses> appliedCourses;
}

@Entity
public class AppliedCourses {
    @Id
    private Long apcid;
    private Long sid;
    private String courseName;
    .
    .
    .
}

用应用课程获取学生实体的 jpql 查询是:

select s from Student s left join fetch s.appliedCourses ac where s.id=:sid

但要求是我只想 select 学生中的几列以及应用课程集

也就是说,我想要这样的东西:

select new com.foo.StudentStat(s.sid, s.name, s.appliedCourses) 
from Student s left join fetch s.appliedCourses ac where s.sid=:sid

StudentStat 结果class:

@Getter
@Setter
@AllArgsConstructor
public class StudentStat {
    private Long sid;
    private String name;
    private Set<AppliedCourses> appliedCourses;
}

以上查询抛出以下异常:

Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list

有没有其他方法可以达到这个要求?

List resultWithAliasedBean = s.createQuery("select s.sid, s.name, s.appliedCourses from Student s left join fetch s.appliedCourses ac where s.sid=:sid").setResultTransformer( Transformers.aliasToBean(StudentStat.class)).list();
StudentStat pojo = (StudentStat) resultWithAliasedBean.get(0);

// 如果您正在使用标准,您可以使用它来转换结果。

criteria.setResultTransformer(Transformers.aliasToBean(StudentStat.class));

如果拥有实体本身未在查询结果中返回,则 JPA 2.1 规范 (JSR 338) 不允许引用提取连接产生的集合:

JSR 338,第 4.4.5.3 节:

The association referenced by the right side of the FETCH JOIN clause must be an association or element collection that is referenced from an entity or embeddable that is returned as a result of the query. It is not permitted to specify an identification variable for the objects referenced by the right side of the FETCH JOIN clause, and hence references to the implicitly fetched entities or elements cannot appear elsewhere in the query.

另一种方法可能是定义一个 EntityGraph,但可能不值得。