日期:2014-05-16  浏览次数:20421 次

HQL主动抓取关联表数据

众所周知,lazy=false时,在取parent的同时也能取得children的数据,但很多情况下这是不需要的,很会影响性能。

可是如果变成lazy=true却又有一些不便之处,比如user和role,要显示user的所有role,如果得到user后,再根据user select出role,这样效率是很差的。

解决方法:利用fetch

select u from User u inner join fetch u.roles (HQL),这样就能在取得user的同时加载role了

使用fetch可能会遇到异常:

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

原因是你可能在select count(*)、sum()等这种统计中使用了fetch,而一般查询是能正确执行的。