hibernate3.0中是可以使用sql语句,但一般还是hql语句的,毕竟我们采用hibernate就是为了使用o/r mapping,如果还用sql就没意义了.除非实在没有办法,不然不要用.
sql的查询:
Query query=session.createSQLQuery( "select {c.*} from CUSTOMERS c where c.Name like:customerName ","c",Customer.class); query.setString("customerName","T%"); List result=query.list();hql的左连接查询: Query query=session.createSQLQuery("from Customer c left join fetch c.orders o" + "where c.name like 'T%' ");List result=query.list();
-------------------------------------------------------------------------------------------------------------
查看文章hibernate中使用session.createSQLQuery(sql)返回值的操作实例2009-07-29 23:25
session.createSQLQuery(sql) 返回的是一个List<Object[]>,对它的操作一般是遍历后,
用Object[]数组的元素来实例化一个对象
如:
/*** @param categoryid 顶级分类id * @return AbstractCategory类型的集合 */public List<AbstractBrand> listAllBrandWithProductCount(int categoryid){ StringBuffer sql=new StringBuffer(); sql.append("select b.id,b.en_name,b.cn_name,count(*) from "); sql.append("brand b, product p "); sql.append("where b.id=p.bid and p.cid=? "); sql.append("group by p.bid "); List<Object[]> result= getSession() .createSQLQuery(sql.toString()) .setParameter(0, categoryid) .list(); List<AbstractBrand> brands=new Vector<AbstractBrand>(); for(Object[] datas :result){ brands.add(new AbstractBrand((Integer)datas[0], datas[1].toString(), datas[2].toString(), ((BigInteger)datas[3]).intValue())); return brands;}