MySQL分段統計SQL寫法 與 Mybatis 報錯:java.math.BigDecimal cannot be cast to java.lang.Integer

來源:互聯網
上載者:User

標籤:

mysql> select    -> sum(case when score<60 then 1 else 0 end) as ‘<60‘,    -> sum(case when score>=60 and score<=69 then 1 else 0 end) as ‘60~69‘,    -> sum(case when score>=70 and score<=79 then 1 else 0 end) as ‘70~79‘,    -> sum(case when score>=80 and score<=89 then 1 else 0 end) as ‘80~89‘,    -> sum(case when score>-90 then 1 else 0 end) as ‘>=90‘    -> from student_course    -> ;+------+-------+-------+-------+------+| <60  | 60~69 | 70~79 | 80~89 | >=90 |+------+-------+-------+-------+------+|    2 |     1 |     1 |     1 |   10 |+------+-------+-------+-------+------+

 採用mybatis時,xml檔案配置如下處理:

  <select id="getScoreStatistics" resultType="map">      select         sum(case when score &lt; 60 then 1 else 0 end) as ‘&lt;60‘,        sum(case when score &gt;= 60 and score &lt;= 69 then 1 else 0 end) as ‘60~69‘,        sum(case when score &gt;= 70 and score &lt;= 79 then 1 else 0 end) as ‘70~79‘,        sum(case when score &gt;= 80 and score &lt;= 89 then 1 else 0 end) as ‘80~89‘,        sum(case when score &gt;= 90 then 1 else 0 end) as ‘&gt;=90‘    from student_course  </select>

mapper介面:

Map<String, Object> getScoreStatistics();

注意,這裡如果使用 Map<String, Integer> 作為傳回值,會報錯:

java.math.BigDecimal cannot be cast to java.lang.Integer

原因是,sum() 的結果是作為 java.math.BigDecimal 來處理的, 而他不能直接轉換成 java.lang.Integer,所以報錯。

正確的處理方法是,返回 Map<String, Object>,然後

{"<60":2,"60~69":1,"70~79":1,"80~89":1,">=90":5}

int count1 = Integer.parseInt(resultMap.get("<60").toString());

通過Object類型的 toString()方法,然後 Integer.parseInt() 這裡才能得到正確的結果。

當然我們也可以直接返回:Map<String, BigDecimal> getScoreStatistics();

然後通過BigDecimal.intValue() 來獲得我們需要的值:

    Map<String, BigDecimal> getScoreStatistics();
Map<String, BigDecimal> resultMap = this.studentCourseMapper.getScoreStatistics();
int count = resultMap.get("<60").intValue();

 總結

1)sql中的 sum() 返回傳回值在mybatis中是作為BigDecimal來返回的,所以我們有兩種方法來處理:

   1> 返回 Object 值,然後通過 Integer.parseInt(obj.toString()); 來得到int值;

   2> 返回 BigDecimal 值,然後通過 BigDecimal.intValue()得到需要的值,應該說我們推薦使用第二種方法。

2)mysql分段統計方法:sum(case when score<60 then 1 else 0 end)

MySQL分段統計SQL寫法 與 Mybatis 報錯:java.math.BigDecimal cannot be cast to java.lang.Integer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.