hibernate常用查询方法

 //hibernate获取个数 

public Long getStarLevel(Long id) {  
    final String hql = "select count(*) from Activity act where act.orginator.id="+id;  
    Long count = (Long)getHibernateTemplate().find(hql).listIterator().next();  
    return count;  
}  


//根据id修改一个对象属性  

  public String updateAttrNameByAttrValue(final String attrName,final String attrValue,final Long id){  
      Object result = this.getHibernateTemplate().execute(  
    new HibernateCallback() {  
        public Object doInHibernate(Session s) throws HibernateException, SQLException {  
                  String hql ="";  
                  String storeHql="";  
                  if(attrName.equals("enabled")){  
                      hql="update User u set u."+attrName+"="+attrValue+" where u.id="+id;  
                      storeHql ="update Store s set s.enabled=0 where s.userId="+id;  
                  }else{  
                      hql="update User u set u."+attrName+"='"+attrValue+"' where u.id="+id;  
                      storeHql ="update Store s set s.enabled=1 where s.userId="+id;  
                  }  
                  Query qStore = s.createQuery(storeHql);  
                  Query q = null;  
                  if(qStore.executeUpdate()>0){  
                      q=s.createQuery(hql);  
                  }  
            return q.executeUpdate();  
        }  
    });  
return String.valueOf(result);  
  }  



查询前50名(日志统计重复日志,按ID分组,按count大小降序,适用于mysql) 

public List getTop50SmsContent() {  
    final String query = "select smsContentId,count(id) cc,(SELECT content from SmsContent sms where sms.id=smsContentId) content from SmsContentClickLog s GROUP BY s.smsContentId ORDER BY cc DESC LIMIT 50";  
    List list = (List)this.getHibernateTemplate().execute(new HibernateCallback() {  
        public Object doInHibernate(Session session) throws HibernateException, SQLException {  
            return session.createSQLQuery(query).list();  
        }  
    });  
    return list;  
}  


根据时间查询List 

List list = (List)this.getHibernateTemplate().execute(new HibernateCallback() {  
            public Object doInHibernate(Session session) throws HibernateException, SQLException {  
            return session.createQuery(hql).setTimestamp("expTime",date).list();  
            }  
        });  

  

posted @ 2013-09-13 17:53  暖流  阅读(304)  评论(0编辑  收藏  举报