java.math.BigInteger cannot be cast to java.lang.L

2019-02-05 21:16发布

I've got List<Long> dynamics. And I want to get max result using Collections. This is my code:

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

This is my 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;

    }

Now I'm getting java.math.BigInteger cannot be cast to java.lang.Long. What's wrong?

7条回答
一夜七次
2楼-- · 2019-02-05 21:29

Try to convert the BigInteger to a long like this

Long longNumber= bigIntegerNumber.longValue();
查看更多
三岁会撩人
3楼-- · 2019-02-05 21:32

You need to add an alias for the count to your query and then use the addScalar() method as the default for list() method in Hibernate seams to be BigInteger for numeric SQL types. Here is an example:

List<Long> sqlResult = session.createSQLQuery("SELECT column AS num FROM table")
    .addScalar("num", StandardBasicTypes.LONG).list();
查看更多
ゆ 、 Hurt°
4楼-- · 2019-02-05 21:35

Better option is use SQLQuery#addScalar than casting to Long or BigDecimal.

Here is modified query that returns count column as Long

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);

Then

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

Related link

查看更多
唯我独甜
5楼-- · 2019-02-05 21:37

Your error might be in this line:

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

where query.list() is returning a BigInteger List instead of Long list. Try to change it to.

List<BigInteger> result = query.list();
查看更多
疯言疯语
6楼-- · 2019-02-05 21:39

Imagine d.getId is a Long, then wrap like this:

BigInteger l  = BigInteger.valueOf(d.getId());
查看更多
不美不萌又怎样
7楼-- · 2019-02-05 21:41

Are you sure dynamics is a List<Long> and not List<BigInteger> ?

If dynamics is a List<Long> you don't need to do a cast to (Long)

查看更多
登录 后发表回答