怎样用hibernate的hql查询查询成map或list
HQL原来还可以这么用呀,呵呵,长见识了!
+++++++++++++++++++++++++++++++++++++++++++++++++
这里制作一个引子,具体内容比较多,而且hibernate文档里的hql篇写的很详细
可以这么用:
Listlist=getHibernateTemplate().find("selectnewmap(t1.c1,t2.c3)fromtable1t1,table2t2wheret1.c1=t2.c2");
这样的话list里的每个元素都是一个map,每个map里包含两个元素
注意:这里的table1和table2都是class名并不是真的表名,毕竟这是hql。除了可以用map还还支持list和自定义的bean。
//HQL-Associations
Stringhql="selects.name,p.name,p.pricefromProductpinnerjoinp.supplierass";
Queryquery=session.createQuery(hql);
Listresults=query.list();
//HQL-Delete
Stringhql="deletefromProductwherename=:name";
Queryquery=session.createQuery(hql);
query.setString("name","Product1");
introwCount=query.executeUpdate();
//HQL-Function
Stringhql="selectmin(product.price),max(product.price)fromProductproduct";
Queryquery=session.createQuery(hql);
Listresults=query.list();
//HQL-FetchAssociationsHQLInnerJoin
Stringhql="fromSuppliersinnerjoinfetchs.productsasp";
Queryquery=session.createQuery(hql);
Listresults=query.list();
//HQL-NamedParameters
Stringhql="fromProductwhereprice>:price";
Queryquery=session.createQuery(hql);
query.setDouble("price",2.0);
Listresults=query.list();
Stringhql="fromProductasproductwhereproduct.supplier=:supplier";
Queryquery=session.createQuery(hql);
query.setEntity("supplier",supplier);
Listresults=query.list();
//HQL-Update
Stringhql="updateSuppliersetname=:newNamewherename=:name";
Queryquery=session.createQuery(hql);
query.setString("name","SupplierName1");
query.setString("newName","s1");
introwCount=query.executeUpdate();
//HQL-where
Stringhql="fromProductwhereprice>2.0andnamelike'P%'";
Queryquery=session.createQuery(hql);
Listresults=query.list();
//HQL-Map
Stringhql="selectnewmap(usr.nameasuserName,usr.passwordaspassword)fromUserusr";
Queryquery=session.createQuery(hql);
Listlist=query.list();
Mapgoods=(Map)list.get(0);
【注】
Stringhql="selectnewmap(usr.nameasuserName,usr.passwordaspassword) fromcom.jason.Userusr";
Stringhql="selectnewmap(usr.nameasuserName,usr.passwordaspassword)fromcom.jason.Userusr";
由于from之前的空格,引起unexpectedtoken: from
//selectnew
给一个构建函数:
publicclassDepartment(Departmentd,IntegeremployeeSize)
然后写成这样:
SELECTnewDepartment(department,count(employee.id))FROM.....
本文转自vtrtbb.spaces.live.com/blog/cns!14B0BD73BAB3D6CD!192.entry