`
webcode
  • 浏览: 5940635 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

Hql语句注意事项总结

 
阅读更多

Hql语句注意事项总结

1.在Hql中使用group by的问题
(1)使用统计函数作为输出结果
selectsum(total),sum(totalup)fromADwhereaid=?andfid=?andvdatetime>=?andvdatetime<=?groupbyaid

(2)使用统计函数作为查询约束条件
selectuidfromMMgroupbyuidhavingcount(*)>?andmin(m_date)<?

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

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

selectcitynamefromMIwherevdatetime>=?andvdatetime<?groupbycityname

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

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

selectcitynamefromMIwherevdatetime>=?andvdatetime<?groupbycityname
selectdistinctcitynamefromMIwherevdatetime>=?andvdatetime<?

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

selectcount(*)fromMipMailconfigasMipMailconfigwhereMipMailconfig.uid<>?andMipMailconfig.email=?--正确
selectcount(MipMailconfig.*)fromMipMailconfigasMipMailconfigwhereMipMailconfig.uid<>?andMipMailconfig.email=?--错误
3.关于Integer和Long的问题
在Hibernate3.2中,所有的计数都要用Long,用Integer的话就会有问题.
Listlist=this.find("selectcount(*)fromMMCasMMCwhereMMC.uid<>?andMMC.email=?",newString[]...{uid,email});
if(list!=null&&!list.isEmpty())...{
longcount=Long.parseLong(list.get(0).toString());
if(count>0)
returntrue;
else
returnfalse;
}



4.关于参数是数组的问题
在实际的工作中,经常遇到这种情况:
(1)要删除一批数据,传过来一个数组,
(2)或者要查询一批数据,查询条件也是传过来一个数组,
这种情况下如何进行处理?
(1)查询数据,查询条件为一个数组,可以有如下两个方法:
<1>直接拼Hql语句
String[]ids=...{"1","2","3"};
Stringstr
="";
for(inti=0;i<ids.length;i++)...{
str
+="'"+ids[i]+"'";
if(i!=(ids.length-1))
str
+=",";
}


Listlist;
list
=appinfoManager.find("fromAppinfowhereidin("+str+")");
if(list!=null)...{
for(inti=0;i<list.size();i++)...{
Appinfoapp
=(Appinfo)list.get(i);
System.out.println(app.getAppname());
}

}

System.out.println(
"共有"+list.size()+"条记录");
<2>利用回调函数处理
publicList getApList()...{
return(List)this.getHibernateTemplate().execute(newHibernateCallback()...{

publicObjectdoInHibernate(Sessionsession)throwsHibernateException,SQLException...{
String[]ids
=...{"1","2","3"};
Stringhql
="fromAppinfowhereidin(:ids)";
Queryquery
=session.createQuery(hql);
Listlist
=query.setParameterList("ids",ids).list();
returnlist;
}

}
);
}
(2)删除数据,参数为数组,利用回调函数
publicvoiddelInArray()...{
this.getHibernateTemplate().execute(newHibernateCallback()...{

publicObjectdoInHibernate(Sessionsession)throwsHibernateException,SQLException...{
String[]ids
=...{"1","2","3"};
Stringhql
="deleteAppinfowhereidin(:ids)";
Queryquery
=session.createQuery(hql);
query.setParameterList(
"ids",ids).executeUpdate();
returnnull;
}

}
);
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics