天天看点

Hql语句注意事项总结(收藏hbcui1984的总结)

1.在Hql中使用group by的问题

(1)使用统计函数作为输出结果

select sum(total),sum(totalup) from AD where aid=? and fid=? and vdatetime>=? and vdatetime<=? group by aid

(2)使用统计函数作为查询约束条件

select uid from MM group by uid having count(*)>? and min(m_date)<?

(3)使用group by 时有关约束条件的问题

如果约束条件是单个字段,则必须用where,并且where要放在group by之前,如:

select cityname from MI where vdatetime>=? and vdatetime<? group by cityname

如果约束条件是统计函数,则要使用having,并且having要放在group by之后,如:(2)

(4)其实,在某些场合,group by可以用distinct代替,如以下两条语句功能相同:

select cityname from MI where vdatetime>=? and vdatetime<? group by cityname

select distinct cityname from MI where vdatetime>=? and vdatetime<?

2.在count()中使用别名问题

select count(*) from MipMailconfig as MipMailconfig where MipMailconfig.uid <> ? and MipMailconfig.email = ?-- 正确

select count(MipMailconfig.*) from MipMailconfig as MipMailconfig where MipMailconfig.uid <> ? and MipMailconfig.email = ?-- 错误

3.关于Integer和Long的问题

在Hibernate3.2中,所有的计数都要用Long,用Integer的话就会有问题.

List list=this.find("select count(*) from MMC as MMC where MMC.uid <> ? and MMC.email = ?",new String[]...{uid,email});

if(list!=null&&!list.isEmpty())...{

long count=Long.parseLong(list.get(0).toString());

if(count>0)

return true;

else

return false;

}

4.关于参数是数组的问题

在实际的工作中,经常遇到这种情况:

(1)要删除一批数据,传过来一个数组,

(2)或者要查询一批数据,查询条件也是传过来一个数组,

这种情况下如何进行处理?

(1)查询数据,查询条件为一个数组,可以有如下两个方法:

<1>直接拼Hql语句

String[] ids = ...{"1","2","3"};

String str="";

for(int i=0;i<ids.length;i++)...{

str+="'"+ids[i]+"'";

if(i!=(ids.length-1))

str+=",";

}

List list;

list = appinfoManager.find("from Appinfo where id in ("+str+")");

if(list!=null)...{

for(int i=0;i<list.size();i++)...{

Appinfo app = (Appinfo)list.get(i);

System.out.println(app.getAppname());

}

}

System.out.println("共有"+list.size()+"条记录");

<2>利用回调函数处理 public List getApList() ...{

return (List)this.getHibernateTemplate().execute(new HibernateCallback() ...{

public Object doInHibernate(Session session) throws HibernateException, SQLException ...{

String[] ids = ...{"1","2","3"};

String hql= "from Appinfo where id in (:ids)";

Query query = session.createQuery(hql);

List list = query.setParameterList("ids", ids).list();

return list;

}

});

}

(2)删除数据,参数为数组,利用回调函数

public void delInArray() ...{

this.getHibernateTemplate().execute(new HibernateCallback() ...{

public Object doInHibernate(Session session) throws HibernateException, SQLException ...{

String[] ids = ...{"1","2","3"};

String hql= "delete Appinfo where id in (:ids)";

Query query = session.createQuery(hql);

query.setParameterList("ids", ids).executeUpdate();

return null;

}

});

}

继续阅读