java.lang.ClassCastException: java.math.BigInteger 不能转换为 java.lang.Long

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18218471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:24:47  来源:igfitidea点击:

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

javasqllong-integer

提问by John Smith

I want to return number of rows using native sql. But console says me java.math.BigInteger cannot be cast to java.lang.Long. What's wrong? This is my method:

我想使用本机 sql 返回行数。但是控制台说我java.math.BigInteger cannot be cast to java.lang.Long。怎么了?这是我的方法:

public Long getNumRows(Integer id){

        Session session = null;

        session = this.sessionFactory.getCurrentSession();
        Query query = session
                .createSQLQuery("SELECT COUNT(*) FROM controllnews WHERE news_id="
                        + id + ";");
        List firstResult = query.list();

        return (Long) firstResult.get(0);


    }

采纳答案by Rohit Jain

Use BigInteger#longValue()method, instead of casting it to Long:

使用BigInteger#longValue()方法,而不是将其强制转换为Long

return firstResult.get(0).longValue();

Seems like firstResult.get(0)returns an Object. One option is to typecast to BigInteger:

似乎firstResult.get(0)返回一个Object. 一种选择是类型转换为BigInteger

return ((BigInteger)firstResult.get(0)).longValue();

But don't do this. Instead use the way provided by Nambari in comments. I'm no user of Hibernate, so I can't provide Hibernate specific solution.

但不要这样做。而是使用 Nambari 在评论中提供的方式。我不是 Hibernate 的用户,所以我无法提供 Hibernate 特定的解决方案。

回答by Aniket Kulkarni

I faced same problem, I used Hibernate Scalar queries as suggested in the comment of @Rohit Jain's answer. Thanks @nambarifor comment.

我遇到了同样的问题,我按照@Rohit Jain's answer的评论中的建议使用了 Hibernate Scalar 查询。感谢@nambari发表评论。

Coming to the problem we have,

来到我们遇到的问题,

Query query = session
            .createSQLQuery("SELECT COUNT(*) FROM controllnews WHERE news_id="
                    + id + ";");  

These will return a List of Object arrays (Object[]) with scalar values for each column in the controllnewstable. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.

这些将返回一个对象数组列表 (Object[]),其中包含controllnews表中每一列的标量值。Hibernate 将使用 ResultSetMetadata 来推断返回的标量值的实际顺序和类型。

To avoid the overhead of using ResultSetMetadata, or simply to be more explicit in what is returned, one can use addScalar():

为了避免使用 ResultSetMetadata 的开销,或者只是为了让返回的内容更加明确,可以使用addScalar():

Query query = session
            .createSQLQuery("SELECT COUNT(*) as count FROM controllnews WHERE news_id="
                    + id + ";").addScalar("count", LongType.INSTANCE);  

This will return Object arrays, but now it will not use ResultSetMetadata but will instead explicitly get the countcolumn as Longfrom the underlying resultset.

这将返回 Object 数组,但现在它不会使用 ResultSetMetadata 而是显式地从基础结果集中获取countLong

How the java.sql.Typesreturned from ResultSetMetaData is mapped to Hibernate types is controlled by the Dialect. If a specific type is not mapped, or does not result in the expected type, it is possible to customize it via calls to registerHibernateTypein the Dialect.

java.sql.Types从 ResultSetMetaData 返回的如何映射到 Hibernate 类型由方言控制。如果特定类型未映射,或未生成预期类型,则可以通过registerHibernateType在方言中调用 来自定义它。



You can use Query#setParametermethod to avoid any mistakes in query as

您可以使用Query#setParameter方法来避免查询中的任何错误

Query query = session
           .createSQLQuery("SELECT COUNT(*) as count FROM controllnews WHERE news_id= :id")
           .addScalar("count", LongType.INSTANCE).setParameter("id",id);  


One confusion when you refer Scalar queriesdocs 4.0, addScalarmethod has second parameter Hibernate.LONG, remember it has been deprecated since Hibernate version 3.6.X
Here is the deprecated document, so you have to use LongType.INSTANCE

当您参考Scalar 查询文档 4.0时的一个困惑,addScalar方法有第二个参数Hibernate.LONG,请记住它自 Hibernate 版本 3.6.X 以来已被弃用
这里是弃用的文档,因此您必须使用LongType.INSTANCE

Related link

相关链接

回答by Ajinz

  String query ="select count(*) from tablename";       
  Number count = (Number) sessionFactory.getCurrentSession().createSQLQuery(query).uniqueResult();
  Long value = count.longValue();

I tried this it works well

我试过这个效果很好