Hibernate Query将count转换为int?

时间:2017-10-06 17:00:07

标签: java sql hibernate

我收到此错误:

  

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

我的想法是检查选择的计数值,但我无法转换它。

附上以下代码。

有什么想法吗?

public List<Map<String, Object>> contaQuery(String sqlCount) throws MensagemException {

    Session session = HibernateUtil.getSession();
    try {

        String sql = sqlCount;
        int query = ((Integer) session.createSQLQuery("select count(*) from (" + sqlCount + ") as subquery")
                .uniqueResult());

        if (query <= 50000) {

            return rodarQuery(sql);
        } else {

            throw new MensagemException("Too many Registers");

        }

    } finally {
        session.close();

    }

}

1 个答案:

答案 0 :(得分:1)

如Farlan的评论所述, 通过调用intValue()

将BigInteger返回值从uniqueResult转换为Integer
final Query query;
final BigInteger bigResult;
final int result;

query = session.createSQLQuery("select count(*) from (" + sqlCount + ") as subquery");
bigResult = (BigInteger)query.uniqueResult();

if (bigResult != null)
{
    result = bigResult.intValue();
}
else
{
    result = ...some value of your choosing, perhaps 0.
)

if (result < 50000)
... stuff