Hibernate 执行SQL语句的count函数返回BigDecimal类型

     当前使用的Hibernate版本是3.2.6,数据库是Oracle11g,当使用 HibernateTemplate 的execute方法执行sql语句(不是 hql 语句)查询的时候,使用count聚合函数,返回结果是 BigDecimal 类型,不是Integer也不是Long,需强转成 BigDecimal 类型,然后调用其对象的 intValue 或 longValue 方法就可以了

与上不同的是,当调用 HibernateTemplate 的 find 方法执行 hql 时,如果hql中有 count 函数,返回的结果是 Long 类型

注:使用Criteria的count查询时返回的是Integer类型。

public int getAlarmCountByFilter(final AlarmFilterBean filter,final int alarmCatelog) {
	return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
		@Override
		public Integer doInHibernate(Session session) throws HibernateException, SQLException {
			Criteria c = session.createCriteria(ActiveAlarmBean.class);
			c.setProjection(Projections.rowCount());
			addFilterRestrictions(c,filter,alarmCatelog);
			return (Integer)c.uniqueResult();
		}
	});
}



----------------------------------------------------------------------------------------------------------分割线-----------------------------------------------------------------------------------------------------------


        将数据库改为MySQL5.1后,执行sql的count语句返回的是BigInteger类型,于是产生ClassCastException异常,为了不再产生类似问题,可将执行SQL语句返回的List<Object[ ]>中已知的数值类型强转成Number,然后调用Number的longValue(),inValue(),floatValue()方法得到想要的数值类型即可。

		final String sql = "select t.TEMPLATE_ID,count(d.TEMPLATE_ID) from RES_INPUT_TEMPLATE t left join "+tableName+" d"
						+" on t.TEMPLATE_ID = d.TEMPLATE_ID "
						+" where t.TEMPLATE_TYPE = "+templateType+" "
						+" group by t.TEMPLATE_ID";
		Map<Long,Integer> idCountMap = new HashMap<Long, Integer>();
		List<Object[]> list = inputTemplateDao.getHibernateTemplate().execute(new HibernateCallback<List<Object[]>>() {
			@SuppressWarnings("unchecked")
			public List<Object[]> doInHibernate(Session session)
					throws HibernateException, SQLException {
				return session.createSQLQuery(sql).list();
			}
		});
		for(Object[] result : list){
			idCountMap.put(((Number)result[0]).longValue(), ((Number)result[1]).intValue());
		}


发布了65 篇原创文章 · 获赞 10 · 访问量 38万+
展开阅读全文

HQL查询中类型转换的问题

06-01

org.hibernate.QueryException: insertion type [org.hibernate.type.BigDecimalType@1d48c] and selection type [org.hibernate.type.DoubleType@293354] at position 2 are not compatible [insert into WsqSqbProfitReportEntity(openId,sqbType,**balanceProfit**,consumeProfit,profitDate,status) select u.openId,'01'**,round(u.userBalance*2.1/36000,2)**,round(u.userConsume*7.5/36000,2),sysdate,'1' from com.lefu.entity.sqb.WsqUserSqbInfoEntity u where u.endDate >= sysdate and u.sqbType = '01'] at org.hibernate.hql.internal.ast.tree.IntoClause.validateTypes(IntoClause.java:125) at org.hibernate.hql.internal.ast.tree.InsertStatement.validate(InsertStatement.java:56) at org.hibernate.hql.internal.ast.HqlSqlWalker.postProcessInsert(HqlSqlWalker.java:731) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.insertStatement(HqlSqlBaseWalker.java:497) at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136) at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:101) at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80) at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:119) at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:215) at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:193) at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1649) at com.lefu.dao.weixin.SqbDao.calculateSqbRate(SqbDao.java:64) at com.lefu.service.impl.weixin.SqbServiceImpl.calculateSqbRate(SqbServiceImpl.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at $Proxy85.calculateSqbRate(Unknown Source) at com.lefu.autoTask.sqb.SqbAutoTask.calculateSqbRate(SqbAutoTask.java:17) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53) at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) ``` ``` 问题相当于向表WsqSqbProfitReportEntity中插入数据,其balanceProfit的类型为BigDecimal,但是,round(u.userBalance*2.1/36000,2)计算出的结果为double类型,导致插入出错,请问应该如何解决呢 谢谢大神指导 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览