Hibernate提供了6種查詢方法分別是:
HQL查詢,對象化查詢Criteria,動態查詢DetachedCriteria,例子查詢,sql查詢,命名查詢。
如果單純的使用hibernate查詢數據庫只需要使用其中的一項就可以完成想要實現的一般功能,但是
從一個點,讓我們掌握6種方法,則提供了更多選擇。每一種方法都有其適用的情況與前提。
在傳遞索引和元素給集合時(elements and indices函數)和傳遞子查詢的結果集時,SQL函數any, some, all, exists, in都是被支持的:
一個用戶角色(User_Role),一個菜單表(Menu),其中Menu表與user_role表有共同的角色字段
select * from menu m where m.permission in (select role_id from user_role u where u.user_id = '13381211803')
可編寫如下Hql 語句完成查詢:
HQL代碼
select Blog from Blog, Book where Blog.author in elements(Book.authors) and Book.id=?
Sql代碼
對應的Sql如下:
from blog, book
where (blog.author in ( select author.authorid from book_author where book.id=book_author.bookid)) and book.id=?