通過百度,google知道hibernate中hql是不支持union的,因此只能藉助native sql了。背景以下:一年前寫了一個hql:sql 原來代碼ide
- 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)"; http://open.189works.com/product/product.htm
- 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)";
主要是找出某我的全部評論過或收藏過的項目。簡單表結構以下:ui project:id owner_id(用戶id)保存項目的基本信息this project_bookmark:uid(用戶id),project_id(收藏的項目的id),owner_id(收藏者的id)google comment_simple:target_type(保存對某種對象的評論,值爲500時表示的對項目的評論),target_id(保存對某種對象的評論,值爲該對象的id),project_id(項目的id),owner_id(評論者的id)spa 因爲這個sql執行時所建的索引沒法使用,並且還形成了三個錶鏈接會有大量的無效的查詢以及重複結果,最後還得要distinct能夠想象執行的效率。hibernate 只好改用union來重寫,須要用到hibernate的native sql,通過努力終於找到能夠用union找出整個對象以及在配置文件中與該對象有關係的對象的方法。htm 與其說是找出來的,不如說是試出來的,代碼以下:對象 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(); http://open.189works.com/product/product.htm
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 ...因此排序時將不起做用,須要咱們本身標出。 |