java.math.BigInteger 不能 cast to java.lang.Long

我有.我想使用获得最大结果。这是我的代码:List<Long> dynamicsCollections

List<Long> dynamics=spyPathService.getDynamics();
        Long max=((Long)Collections.max(dynamics)).longValue(); 

这是我的:getDynamics

public List<Long> getDynamics() {

        Session session = null;

        session = this.sessionFactory.getCurrentSession();
        Query query = session
                .createSQLQuery("SELECT COUNT(*) FROM SpyPath WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY) GROUP BY DATE(time) ORDER BY time;");

        List<Long> result = query.list();
        return result;

    }

现在我得到.怎么了?java.math.BigInteger cannot be cast to java.lang.Long


答案 1

更好的选择是使用 SQLQuery#addScalar 而不是强制转换为 或 。LongBigDecimal

下面是将列返回为的已修改查询countLong

Query query = session
             .createSQLQuery("SELECT COUNT(*) as count
                             FROM SpyPath 
                             WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY) 
                             GROUP BY DATE(time) 
                             ORDER BY time;")
             .addScalar("count", LongType.INSTANCE);

然后

List<Long> result = query.list(); //No ClassCastException here  

相关链接


答案 2

您的错误可能位于以下行中:

List<Long> result = query.list();

其中 query.list() 返回的是 BigInteger List 而不是 Long list。尝试将其更改为。

List<BigInteger> result = query.list();