gpt4 book ai didi

java - 提取的所有者不存在

转载 作者:行者123 更新时间:2023-12-02 11:36:04 25 4
gpt4 key购买 nike

我正在尝试在这里学习 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)

学生和指南具有多对一的关系..

注意:我知道用指南替换选择查询中的学生可以解决问题,但我试图找出为什么它不能以相反的方式工作。

最佳答案

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

这里你实际上是在告诉hibernate:

Guide join Student 表中获取所有学生,并确保在 Guide 实体中立即获取对 Student 的引用。但您没有 Guide 实体

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

select student from Student student join fetch 
student.guide guide

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

关于java - 提取的所有者不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48922807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com