經過百度,google知道hibernate中hql是不支持union的,所以只能借助native sql了。背景如下:一年前寫了一個hql:
原來代碼
- String countHql2 = "select count(distinct p) from Project as p,CommentSimple as c,ProjectBookmark as b where ("
- + "c.owner.id=? and p.id=c.targetId and c.targetType=500) or (b.user.id=? and p.id=b.project.id)";
- String hql2 = "select distinct p from Project as p,CommentSimple as c,ProjectBookmark as b where ( "+ "c.owner.id=? and p.id=c.targetId and c.targetType=500) or (b.user.id=? and p.id=b.project.id)";
主要是找出某個人所有評論過或收藏過的項目。簡單表結構如下:
project:id owner_id(用戶id)保存項目的基本信息
project_bookmark:uid(用戶id),project_id(收藏的項目的id),owner_id(收藏者的id)
comment_simple:target_type(保存對某種對象的評論,值為500時表示的對項目的評論),target_id(保存對某種對象的評論,值為該對象的id),project_id(項目的id),owner_id(評論者的id)
由於這個sql執行時所建的索引無法使用,而且還造成了三個表連接會有大量的無效的查詢以及重復結果,最後還得要distinct可以想象執行的效率。
只好改用union來重寫,需要用到hibernate的native sql,經過努力終於找到可以用union找出整個對象以及在配置文件中與該對象有關系的對象的方法。
與其說是找出來的,不如說是試出來的,代碼如下:
union
- String sql1 = "SELECT COUNT(*) FROM(SELECT p.id FROM project p,comment_simple c WHERE p.id=c.target_id AND c.target_type=500 AND c.uid=" + userId
- + " UNION SELECT pr.id FROM project pr,project_bookmark b WHERE pr.id=b.project_id AND b.uid=" + userId + ") AS temp";
- String sql2 = "(SELECT {p.*} FROM project p,comment_simple c WHERE p.id=c.target_id AND c.target_type=500 AND c.uid=" + userId + ")"
- + "UNION"
- + "(SELECT {p.*} FROM project p,project_bookmark b WHERE p.id=b.project_id AND b.uid=" + userId + ")LIMIT " + (pageIndex - 1) * maxPerPage + "," + maxPerPage;
- SQLQuery query = this.getSession().createSQLQuery(sql1);
- Integercount=Integer.valueOf(((BigInteger)query.uniqueResult()).toString());
- SQLQuery query2 = this.getSession().createSQLQuery(sql2);
- query2.addEntity("p", Project.class);
- List<Project> list = query2.list();
sql1符合條件的項目的總數。sql2求出符合條件項目的某一頁。
要注意的是:sql2中{p.*}要寫成一樣的。
簡而言之:select {a.*} from A a where ... union select {a.*} from A a where...
如果還要排序的話sql2換成sql3:
需要order by時
- String sql3 = "(SELECT {p.*},p.created FROM project_hz p,comment_simple c WHERE p.id=c.target_id AND c.target_type=500 AND c.uid=" + userId + ")"
- + "UNION"
- + "(SELECT {p.*} ,p.created FROM project_hz p,project_bookmark b WHERE p.id=b.project_id AND b.uid=" + userId + ") ORDER BY created LIMIT " + (pageIndex - 1) * maxPerPage + "," + maxPerPage;
要注意的是p.created(需要排序的那個字段) 要個別標出,因為hibernate在轉換為sql是會寫成 select created as ...所以排序時將不起作用,需要我們自己標出。
這裡只是找出了一個解決方案,因為對hibernate的調優不是特別熟悉這樣做會不會造成另外不好的影響就不清楚了,如果有高手看到有什麼問題,或者有更好的方法。請不吝賜教