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

前端 未结 8 697
醉话见心
醉话见心 2020-12-09 15:44

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

List dynamics=spy         


        
相关标签:
8条回答
  • 2020-12-09 15:58

    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();
    
    0 讨论(0)
  • 2020-12-09 16:04

    It's a very old post, but if it benefits anyone, we can do something like this:

    Long max=((BigInteger) Collections.max(dynamics)).longValue(); 
    
    0 讨论(0)
  • 2020-12-09 16:05

    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

    • Hibernate javadocs
    • Scalar queries
    • 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
    • My previous answer
    0 讨论(0)
  • 2020-12-09 16:06

    I'm lacking context, but this is working just fine:

    List<BigInteger> nums = new ArrayList<BigInteger>();
    Long max = Collections.max(nums).longValue(); // from BigInteger to Long...
    
    0 讨论(0)
  • 2020-12-09 16:06

    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)

    0 讨论(0)
  • 2020-12-09 16:08

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

    BigInteger l  = BigInteger.valueOf(d.getId());
    
    0 讨论(0)
提交回复
热议问题