如何在Hibernate中使用union

 

 

通过百度,google知道hibernate中hql是不支持union的,因此只能借助native sql了。背景以下:一年前写了一个hql:sql

原来代码ide

      
      
      
      
  1. String countHql2 = "select count(distinct p) from Project as p,CommentSimple as c,ProjectBookmark as b where (" 
  2. "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
  3.      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排序

      
      
      
      
  1. 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 
  2. " UNION SELECT pr.id FROM project pr,project_bookmark b WHERE pr.id=b.project_id AND b.uid=" + userId + ") AS temp"
  3. 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 + ")" 
  4. "UNION" 
  5. "(SELECT {p.*} FROM project p,project_bookmark b WHERE p.id=b.project_id AND b.uid=" + userId + ")LIMIT " + (pageIndex - 1) * maxPerPage + "," + maxPerPage; 
  6. SQLQuery query = this.getSession().createSQLQuery(sql1); 
  7. Integercount=Integer.valueOf(((BigInteger)query.uniqueResult()).toString()); 
  8. SQLQuery query2 = this.getSession().createSQLQuery(sql2); 
  9. query2.addEntity("p", Project.class); 
  10. 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时

      
      
      
      
  1. 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 + ")" 
  2. "UNION" 
  3. "(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 ...因此排序时将不起做用,须要咱们本身标出。

相关文章
相关标签/搜索