【发布时间】:2018-02-22 08:34:02
【问题描述】:
我正在尝试在这里学习hibernate并遇到了这个类:
HelloWorldClient.java
public class HelloWorldClient {
public static void main(String[] args) {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("hello-world");
EntityManager em = emf.createEntityManager();
EntityTransaction txn = em.getTransaction();
try {
txn.begin();
Query query = em.createQuery("select student from Guide guide join fetch
guide.students student");
List<Student> students = query.getResultList();
System.out.println(students);
txn.commit();
} catch (Exception e) {
if (txn != null) {
txn.rollback();
}
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
}
执行查询时出现错误:
java.lang.IllegalArgumentException: org.hibernate.QueryException: query
specified join fetching, but the owner of the fetched association was not
present in the select list [FromElement{explicit,not a collection join,fetch
join,fetch non-lazy properties,classAlias=student,role=entity.Guide.students,tableName=Student,tabl
eAlias=students1_,origin=Guide guide0_,columns={guide0_.id ,className=entity.Student}}] [select student from entity.Guide guide join fetch
guide.students student]at Impl.java:294)
at client.HelloWorldClient.main(HelloWorldClient.java:31)
学生和向导是多对一的关系。
注意:我知道将 select 查询中的 student 替换为 guide 可以解决问题,但我试图找出为什么它不能反过来工作。
【问题讨论】:
-
JOIN FETCH基本上是请求加载候选对象的其他字段,您将在其中返回候选对象,因此毫无意义。在您的情况下,您没有返回候选对象。可以说,尽管 JPA 提供者不应该抛出异常,而只是忽略它,因为 JOIN FETCH 没有任何意义。