Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

java - Join fetch: "query specified join fetching, but the owner of the fetched association was not present in the select list"

I have a following code:

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);
}

It raises an exception:

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

In the result I wan to get only codes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

join fetch val.classDAO.b means "when fetching val, also fetch the classDAO linked to the val". But your query doesn't fetch val. It fetches val.code only. So the fetch makes no sense. Just remove it, and everything will be fine:

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

Some notes, though:

  • doing a left join and then adding a retriction like classDAO.id = ? means that the join is in fact an inner join (since classDAO can't be null and have the given ID at the same time)
  • naming your entities XxxDAO is very confusing. DAOs and entities are not the same thing at all.

Given the above, the query can be rewritten as

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...