distinct在HQL中使用

来源:互联网 发布:二次开发 软件著作权 编辑:程序博客网 时间:2024/04/25 08:10
  1. public static List findHBDH() {
  2.         Transaction tx = null;
  3.         Session session = SessionManager.currentSession();
  4.         List<Long> list = new ArrayList<Long>();
  5.         try {
  6.             tx = session.beginTransaction();
  7.             StringBuffer hqlStr = new StringBuffer(
  8.                     "select distinct xx.b1 from XXX xx");
  9.             Query qry = session.createQuery(hqlStr.toString());
  10.             Iterator it = qry.list().iterator();
  11.             while (it.hasNext()) {
  12.                 list.add((Long)it.next());
  13.             }
  14.         } catch (Exception e) {
  15.             if (tx != null) {
  16.                 try {
  17.                     tx.rollback();
  18.                 } catch (HibernateException ex) {
  19.                     ex.printStackTrace();
  20.                 }
  21.             }
  22.             e.printStackTrace();
  23.             return null;
  24.         } finally {
  25.             try {
  26.                 SessionManager.closeSession();
  27.             } catch (Exception e) {
  28.                 e.printStackTrace();
  29.             }
  30.         }
  31.         return list;
  32.     }
  33. public static void main(String[] args) {
  34.         //测试
  35.         List list = new ArrayList();
  36.         try{
  37.             list = findHBDH();
  38.             for(int i=0;i<=list.size()-1;i++){
  39.                 System.out.println(list.get(i));
  40.             }
  41.         }catch(Exception e){
  42.             e.printStackTrace();
  43.         }
  44. }

 

注意两点: HQL的写法"select distinct 别名.字段 from 映射类名 别名"。。。

                  如何存储到list。。。 list.add((Long)it.next())。。。

原创粉丝点击