HQL中的select子句

来源:互联网 发布:多源异构数据 编辑:程序博客网 时间:2024/05/16 04:35
一、select子句简介:



二、以对象数组形式返回选择的属性:

publicvoidtestSelectClauseObjectArray(){
           String hql="select country.ccode,country.cname from Country as country";
           Session session=CustomSessionFactory.getSession();
           Query query=session.createQuery(hql);
           List<Object[]> countries=query.list();
           for(Object[] objects:countries){
                System.out.println("编码:"+objects[0]+"   名称:"+objects[1]);
           }
           CustomSessionFactory.closeSession();
     }
 


三、以list形式返回选择的属性:

publicvoidtestSelectClauseList(){
           String hql="select new list(country.ccode,country.cname) from Country as country";
           Session session=CustomSessionFactory.getSession();
           Query query=session.createQuery(hql);
           List<List> lists=query.list();
           for(List list:lists){
                System.out.println("编码:"+list.get(0)+"  名称:"+list.get(1));
           }
           CustomSessionFactory.closeSession();
     }
 


四、以Map的形式返回选择的属性:


publicvoidtestSelectClauseMap(){
           String hql="select new map(country.ccode as ccode,country.cname as cname) from Country as country";
           Session session=CustomSessionFactory.getSession();
           Query query=session.createQuery(hql);
           List<Map> maps=query.list();
           for(Map map:maps){
                System.out.println("编码:"+map.get("ccode")+"     名称:"+map.get("cname"));
           }
           CustomSessionFactory.closeSession();
     }
                                  


五、以自定义类型返回选择的属性:


publicvoidtestSelectClauseSelf(){
           String hql="select new Country(country.ccode,country.cname) from Country as country";
           Session session=CustomSessionFactory.getSession();
           Query query=session.createQuery(hql);
           List<Country> countries=query.list();
           for(Countrycountry:countries){
                System.out.println("编码:"+country.getCcode()+"     名称:"+country.getCname());
           }
           CustomSessionFactory.closeSession();
     }




六、使用distinct关键字去除重复的记录:


publicvoidtestDistinct(){
           String hql="select distinct country.cname from Country as country";
           Session session=CustomSessionFactory.getSession();
           Query query=session.createQuery(hql);
           List<Object> list=query.list();
           for(Object country:list){
                System.out.println("国家:"+country);
           }
           CustomSessionFactory.closeSession();
     }