【问题标题】:Owner of the fetching not present获取的所有者不存在
【发布时间】: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 没有任何意义。

标签: java hibernate jpa hql


【解决方案1】:

Join fetch 在这里没有意义,因为它是一个强制加载关系的性能提示。

这里你实际上是在告诉休眠:

Guide join Student 表中取出所有学生,并确保急切地获取Guide 实体中对Student 的引用。但是你没有Guide 实体

如果您想要学生,只需从他们的表中选择学生,如果您需要与 Guide 的关系,请声明它。

select student from Student student join fetch 
student.guide guide

或者在这种情况下完全删除 fetch

【讨论】:

    猜你喜欢
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 2015-04-11
    • 2021-02-13
    • 2017-12-09
    相关资源
    最近更新 更多