经典hql语句

1.hql更新
String hql = "update PhUser set realName=?";
int row=this.getSession().createQuery(hql).setString(0, "小李想").executeUpdate();
PhUser 类名
2.hql删除
String hql = "delete PhUser a where a.userId=2";
int row=this.getSession().createQuery(hql).executeUpdate();
还有个这种的格式:
final String hql = "delete PhRoleFunction as a where a.roleId = "
+ roleId;
this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
return session.createQuery(hql).executeUpdate();
}
});更新也可以写成这样的格式
3.hql单表查询
String hql = "from PhUser a where a.userId=" + userId;
List list = this.getHibernateTemplate().find(hql);
4.hql多表查询
(1)String hql = "select new map(a.CUId as CUId,a.unitName as unitName,b.CUFId as CUFId,b.UFName as UFName) from PhCorrelativeUnit a,PhCorrelativeUnitFunction b where a.CUId=b.CUId";
List list = this.getHibernateTemplate().find(hql);
多个表的字段放到map中,map的键值就是as后面的别名,如果没有as就是字段名
(2) String hql = "select new com.phantom.appeal.action.bean.DealPaper(a.id as id,a.billId as billId,a.state as     state,a.creator as creator,a.createtime as createtime ,b.eventContent as eventContent ,c.realName as     realName,b.billCode as billCode,b.citName as citName ) from PhDealBill a,PhAcceptBill b,PhUser c where    a.departmentId="+ billid+ " and a.state=0 and a.billId=b.billId and a.creator =c.userId order by a.billId";
return this.getHibernateTemplate().find(hql);
另外就是写一个类,对应你要查询的字段,这里的类名是new com.phantom.appeal.action.bean.DealPaper,里面对应查询的字段名
5.得到记录数
String hql = "select count(*) from PhUser";
List list = this.getHibernateTemplate().find(hql);
return ((Long) list.get(0)).intValue();

 

 

五种检索方式的使用场合和特点:

HQL : 是面向对象的查询语言,同SQL有些相似是Hib中最常用的方式。
       查询设定各种查询条件。
       支持投影查询,检索出对象的部分属性。
       支持分页查询,允许使用having和group by
       提供内制的聚集函数,sum(),min(),max()
       能调用用户的自定义SQL
       支持子查询,嵌入式查询
       支持动态绑定参数
建议使用Query接口替换session的find方法。
   Query Q = session.createQuery("from customer as c where c.name = :customerName" + "and c.age = :customerAge");
   query.setString ("customerName" , "tom");
   query.setInteger("customerAge" , "21");
   list result = query.list();
QBC : QBCAPI提供了另一种方式,主要是Criteria接口、Criterion接口和Expression类
   Criteria criteria = session.createCriteria(customer.class);
   Criterion criterion1 = Expression.like("name","t%");
   Criterion criterion2 = Expression.eq("age",new Integer(21));
   Critera = criteria.add(criterion1) ;
   Critera = criteria.add(criterion2) ;
   list result = criteria.list();
   或是: list result = session.createCriteria(Customer.class).add(Expression.eq("this.name","tom")).list();
SQL : 采用HQL和QBC检索时,Hib生成SQL语句适用所有数据库。
   Query query = session.createSQLQuery("select {c.*} from customers c where c.name like : customername " + "and c.age = :customerage","c",customer.calss);
   query.setString("customername","tom");
   query.setInteger("customerage","21");
   list result = query.list();
/////////////多态查询
   HQL :session.createQuery("from employee");
   QBC :session.createCriteria(employee.class);
   HQL : session.createQuery("from hourlyEmployee");
   QBC : session.createCriteria(hourlyEmployee.class);
   下面的HQL查询语句将检索出所有的持久化对象:
   from java.lang.Object ;
   from java.io.serializable ;
////////////查询的排序
   1'查询结果按照客户姓名升序排列:
   HQL :
        Query query = session.createQuery ("from customer c order by c.name");
   QBC :
        Criteria criteria = session.createCriteria(customer.class);
        criteria.addOrder(order.asc("name"));
   HQL :
        Query query = session.createQuery ("from customer c order by c.name asc , c.age desc");
   QBC :
        Criteria criteria = session.createCriteria(customer.class);
        criteria.addOrder(order.asc ("name"));
        criteria.addOrder(order.desc("age"));

        import net.sf.hibernate.pression.Order
        import mypack.Order
        ...........
        Criteria criteria = session.createCritria (mypack.Order.class);
        criteria.addOrder(net.sf.hibernate.Order.asc("name"));
///////////HQL语句的参数绑定Query接口提供了绑定各种Hib映射类型的方法。
        setBinary()
        setString()
        setBoolean()
        setByte()
        setCalendar()
        setCharacter()
        setDate()
        setDouble()
        setText()
        setTime()
        setTimestamp()
        setEntity()//把参数与一个持久化类的事例绑定lsit result = session.createQuery("from order o where o.customer =            :customer").setEntity("customer" , customer).list ;
        setParameter()//绑定任意类型的参数
        setProperties()//把命名参数与一个对象的属性值绑定 Query query = session.createQuery("from customer c where c.name =:     name " + "and c.age =:age" );
        Query.setProperties(customer);

过滤查询结果中的重复元素
     使用Set集合来去除重复元素;或是使用distinct元素
     Iterator iterator = session.createQuery("select distinct c.name from customer ").list().iterator();
     while(iterator.hasnext()){
           String name = (String) it.next() ;
     }
///////////使用聚集函数
count(); 记录的条数
min();   求最小值
max();   求最大值
avg();   求平均值
sum();   求和
1'查询customer中的所有记录条数
   integer i = (Integer) session.createQuery("select count(*) from customer").uniqueResult();
2'查询customer中的所有客户的平均年龄
   integer i = (Integer) session.createQuery("select avg(c.age) from customer c ").uniqueResult();
3'查询customer中的客户年龄的最大值、最小值
   object [] i = (Integer) session.createQuery("select max(c.age),min(c.age) from customer c ").uniqueResult();
   Integer Maxage = (Integer) i [0];
   Integer Minage = (Integer) i [1];
4'统计customer中的客户的名称数目,忽略重复的姓名
   Integer cout = (Integer) session.createQuery("select count(distinct c.name) from customer c").uniqueResult();
////////////使用分组查询
1'按姓名分组,统计customer中的相同姓名的记录数目
   Iterator iterator = (Integer) session.createQuery("select c.name ,count(c) from customer c group by c.name").list.iterator();
   while(iterator.hasnext()){
         object[] p = (objcet[])iterator.next();
         String name = p[0];
         Integer cout = p[1];
   }
2'按客户分组,统计每个客户的订单数量
   Iterator iterator = session.crateQuery("select c.id ,c.name , count(o) from customer c join c.order o group by c.id ").list().iterator;
   while(iterator.hasnext()){
         object[] p = (objcet[])iterator.next();
         Integer id = p[0]
         String name = p[1];
         Integer cout = p[2];
   }
3'统计每个客户的订单总价
   Iterator iterator = session.crateQuery("select c.id ,c.name,sum(o.price) from customer c join c.order o group by c.id").list.iterator();
   while(iterator.hasnext()){
         object[] p = (objcet[])iterator.next();
         Integer id = p[0]
         String name = p[1];

你可能感兴趣的:(sql,C++,c,Hibernate,C#)