草庐IT

java - 加入获取 : "query specified join fetching, but the owner of the fetched association was not present in the select list"

coder 2024-03-22 原文

我有以下代码:

public class ValueDAO  implements BusinessObject<Long> {

    private Long id;
    private String code;
    private ClassDAO classDAO ;
        ....
}

public List<String> getCodesByCodeClass(Long classId) {
    String select = "select distinct val.code from ValueDAO val left " +
        "join fetch val.classDAO ";
    String where = "where val.classDAO.id = ? order by val.code";

    return getHibernateTemplate().find(select + where, classId);
}

它引发了一个异常:

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

在结果中我只想得到代码。

最佳答案

join fetch val.classDAO.b表示“在获取 val 时,还获取链接到 classDAOval ”。但是您的查询没有获取 val .它获取 val.code只要。所以抓取没有意义。只需删除它,一切都会好起来的:

select distinct val.code from ValueDAO val 
left join val.classDAO classDAO
where classDAO.id = ? 
order by val.code

一些注意事项:

  • 进行左连接,然后添加限制,如 classDAO.id = ?意味着连接实际上是一个内部连接(因为 classDAO 不能为 null 并且同时具有给定的 ID)
  • 将您的实体命名为 XxxDAO 非常令人困惑。 DAO 和实体根本不是一回事。

鉴于上述,查询可以重写为

select distinct val.code from ValueDAO val 
where val.classDAO.id = ? 
order by val.code

关于java - 加入获取 : "query specified join fetching, but the owner of the fetched association was not present in the select list",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12496945/

有关java - 加入获取 : "query specified join fetching, but the owner of the fetched association was not present in the select list"的更多相关文章

随机推荐