java - Spring Jdbc 模板返回 Int 为 Long?

标签 java mysql spring-jdbc

我的 MySQL 表中有 3 列,2 列是 INT,1 列是 VARCHAR。

我收到类转换异常:java.lang.ClassCastException:java.lang.Long 无法转换为 java.lang.Integer。这是我的代码:

    List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql);
    for (Map row : rows) {
        Customer customer = new Customer();
            // throws ClassCastException
            // customer.setCustId((Integer)(row.get("CUST_ID")));

        customer.setCustId((Long)(row.get("CUST_ID")));  // had to change custId field in bean to long
        customer.setName((String)row.get("NAME"));

        // work around
        customer.setAge(((Long)row.get("AGE")).intValue());

        customers.add(customer);
    }

我的问题是为什么我必须将它转换为 Long?是因为MySQL中允许的最大INT值和java中允许的最大INT值不一样吗?

最佳答案

MySQL 主键整数是无符号的,Java int 是有符号的。位数相同,但无符号具有完整的 4G 正范围。

关于java - Spring Jdbc 模板返回 Int 为 Long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7548616/

相关文章:

java - 单击按钮时 setRequestedOrientation 后自动旋转不起作用

java - Android:在回收 View 中获取用户在屏幕上的确切位置

mysql - 使用 IF 语句避免在 SQL 查询中添加重复项?

mysql - 如何最好地合并四个大表

java - SQL Server + Spring JAVA 应用程序的奇怪性能问题

java - OSGI号导入限制

java - 如何检索数据库中最后插入的值?

mysql - 联合查询中的排序错误

mysql - 看到连接被放弃警告,随后 SSL 对等点错误关闭

spring - spring boot 测试中的事务未回滚