Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

hibernate - java.math.BigInteger cannot be cast to java.lang.Long

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...