关于Hibernate select count(*)返回值为Long还是Integer?

关于Hibernate select count(*)返回值为Long还是Integer?

我这里把代码贴一下: 

Java code  @Override
public
int countAllSubject() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
return ((Long) session.createQuery(
"select count(*) from Post where idParent=0").iterate().next())
.intValue();
}



在我的机器上,用Long作为返回值,运行正常,如果改成Integer,则报如下错误 
Java codetype Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:522)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

root cause

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
net.java2000.notepad.service.impl.hibernate.PostServiceHibernateImpl.countAllSubject(PostServiceHibernateImpl.java:24)
org.apache.jsp.jsph.index_jsp._jspService(index_jsp.java:93)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

note The full stack trace of the root cause is available in the Apache Tomcat/6.0.16 logs.




但是,有几个网友却是正好相反,他们直接运行报 

java.lang.ClassCastException: java.lang.Integer  

改成Integer却正常了。 


希望大家使用Hibernate比较熟悉的人,确认一下,大家随意使用 count(*) 然后读取看看,到底是Integer,还是 Long 



解决方案:
关于在Hibernate里使用select count(*) 返回值的问题说明 
由于我使用的是Hibernate 3.2版本,经确认,这个版本已经把以前返回 Integer的改成了 Long, 
因为JPA里面的返回值规定是Long, Hibernate为了兼容这个,所以修改了返回值。 

如果你从Hibernate 3.0.x/3.1.x升级到最新的3.2版,一定要注意,3.2版的很多sql函数如count(), sum()的唯一返回值已经从Integer变为Long,如果不升级代码,会得到一个ClassCastException。 


出处 http://hi.baidu.com/chenleibupt/item/d08ee931967f3fc51b9696db

你可能感兴趣的:(Hibernate)