hibernate 的hql查詢語句中使用fetch的注意點

hibernate 的hql中使用fetch 可以取消lazy load,有效減少發出的sql查詢語句(多sql語句意味着多次訪問數據庫,加大連接次數,降低使用效率)。提高數據庫的訪問效率。但是在使用fetch的問題中仍可能會出現一些問題:這裏主要有三個model   :User(one)<-------------->(many)UserRole(many)<---------------------->(one) Role,簡單的說 這裏user和role是many2many的關係,通過一個userRole轉換爲兩個many2One的關係。

這裏有以下幾個方法:

public List<Role> listUserRoles(int userId) 



這個方法要通過userId關聯UserRole對象查找Role對象。這裏可以使用"select ur.role from UserRole ur where ur.user.id = ?"直接查詢,不使用left join可以得到結果,但是如果使用

"select ur.role fromUserRoleur left join  ur.role r left join fetch ur.user u  where u.id = ?";  這時候會發現運行時出現

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=r,role=null,tableName=t_role,tableAlias=role1_,origin=t_user_role userrole0_,columns={userrole0_.r_id ,className=org.konghao.cms.model.Role}}] [select ur.role from org.konghao.cms.model.UserRole ur left join fetch ur.role r left join fetch ur.user u  where u.id = ?]
	

錯誤。如果將fetch去除則不會出現這樣的問題。這裏主要的原因參考

http://zhan.renren.com/itsavingdebug?gid=3602888498024713423&checked=true

的說明。

簡單的說from的左右兩邊如果不是同一個類Select A.B from A。這裏不能使用fetch。如果from的左右兩邊是同一個類:select A from A  //當然這裏的select A可以去除。這樣的形式的話就可以使用fetch解除lazy load的問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章