首页 > 解决方案 > java.lang.Integer 不能转换为 java.math.BigInteger

问题描述

我是hibernate和Mssql的新手。我正在研究 MySQL 到 Mssql 的集成。

我正面临这个例外:

java.lang.ClassCastException:java.lang.Integer 无法转换为 java.math.BigInteger

我的代码是:

long salesAlertsCount = ((BigInteger)HibernateUtil.getHibernateSession()
        .createSQLQuery("SELECT COUNT(a.id) FROM Activity as a,Lead as l WHERE a.what_id=l.id and l.deleted=0 and "
        + (currentUser.isAdmin() ? "a.tenant_id="+currentUser.getTenant_id():" (a.owner_id="+currentUser.getId()
        + " or a.createdBy_id="+currentUser.getId()+")")
        + " and "
        + (currentUser.isAdmin()?"l.tenant_id="+currentUser.getTenant_id():" (l.owner_id="+currentUser.getId()+")")
        + " and a.deleted=0 and a.action="
        + Constants.ACTIVITY_ACTION_SEND_SALES_ALERT
        + ""
        + " and a.viewed=0 AND a.created>='"
        + beginingOfMonth
        + "' ").uniqueResult()).longValue();

这是我的代码,我之前被困在这里,这段代码在 MySQL 中工作,但现在当我集成到 Mssql 中时,它显示了该异常。

先感谢您

标签: javahibernate

解决方案


请尝试使用BigInteger.valueOf(), 而不是(BigInteger).

long salesAlertsCount = BigInteger.valueOf(HibernateUtil.getHibernateSession().createSQLQuery("SELECT COUNT(a.id) FROM Activity as a,Lead as l WHERE a.what_id=l.id and l.deleted=0 and "+(currentUser.isAdmin()?"a.tenant_id="+currentUser.getTenant_id() +" (a.owner_id="+currentUser.getId() +" or a.createdBy_id="+currentUser.getId()+")")+" and "+(currentUser.isAdmin()?"l.tenant_id="+currentUser.getTenant_id():" (l.owner_id="+currentUser.getId()+")")+" and a.deleted=0 and a.action="+Constants.ACTIVITY_ACTION_SEND_SALES_ALERT+"" + " and a.viewed=0 AND a.created>='"+beginingOfMonth+"' ").uniqueResult()).longValue();

此外,您应该更改在 HQL 中设置参数的方式。这可能代表严重的安全风险,允许用户注入恶意 sql 查询。相反,您应该使用如下所示的 hql 参数。

Query query = HibernateUtil.getHibernateSession().createQuery("SELECT count(a.id) FROM Activity a, Lead l where a.what_id = l.id and a.owner_id = :owner_id"); \\ Add the rest of the code
query.setParameter("owner_id", currentUser.getId());

您可以在以下链接中阅读更多内容。


推荐阅读