mybatis竟然報"Invalid value for getInt()"

eaglelihh發表於2021-10-31

背景

使用mybatis遇到一個非常奇葩的問題,錯誤如下:

Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'name' from result set.  Cause: java.sql.SQLException: Invalid value for getInt() - 'hhhh'

場景

還原一下當時的情況:

public interface UserMapper {
    @Results(value = {
            @Result(property = "id", column = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
            @Result(property = "age", column = "age", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR)
    })
    @Select("SELECT id, name, age FROM user WHERE id = #{id}")
    User selectUser(Long id);
}

@Data
@Builder
public class User {
    private Long id;
    private Integer age;
    private String name;
}

public class MapperMain {
    public static void main(String[] args) throws Exception {
        MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8");

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(UserMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            System.out.println(userMapper.selectUser(1L));
        }
    }
}

資料庫如下:

上面是一個很簡單的例子,就是根據id選出使用者的資訊,執行結果如下:

User(id=1, age=2, name=3)

沒有任何問題,但是我再往資料庫裡插入一條資料,如下:

MapperMain類中增加一行程式碼,如下:

System.out.println(userMapper.selectUser(2L));

執行結果如下:

User(id=1, age=2, name=3)
### Error querying database.  Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'name' from result set.  Cause: java.sql.SQLException: Invalid value for getInt() - 'hhhh'
……

可以看出第一條查詢沒有問題,第二條查詢就報錯了

初探

其實我的直覺告訴我,是不是因為User類裡欄位順序和SQL語句裡select欄位的順序不一致導致的,那就來試一下吧

改一下User類裡欄位的順序:

@Data
@Builder
public class User {
    private Long id;
    private String name;
    private Integer age;
}

結果如下:

User(id=1, name=3, age=2)
User(id=2, name=hhhh, age=3)

果不其然,直覺還是很6的

或者改一下SQL語句裡select欄位的順序:

@Data
@Builder
public class User {
    private Long id;
    private Integer age;
    private String name;
}

public interface UserMapper {
    @Results(value = {
            @Result(property = "id", column = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
            @Result(property = "age", column = "age", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR)
    })
    @Select("SELECT id, age, name FROM user WHERE id = #{id}")
    User selectUser(Long id);
}

以我們的直覺,結果肯定也沒問題,果不其然,如下:

User(id=1, age=2, name=3)
User(id=2, age=3, name=hhhh)

再探

其實到上一步,問題已經解決了,可以繼續幹活了,但是搞不懂為什麼,心裡總覺得不踏實。

bugdebug開始,從下面的入口開始:

追蹤到如下:

可以看出User這個類是有建構函式的,而且是包含所有欄位的建構函式
利用這個建構函式建立例項的時候,引數的順序就是SQL語句選擇欄位的順序,不會根據對映關係去選擇
所以就出現了型別不匹配

那我們再來看一下問什麼會有一個這樣的建構函式產生,直覺告訴我是@Builder這個註解

一起來看一下User編譯後的結果:

public class User {
    private Long id;
    private String name;
    private Integer age;

    User(final Long id, final String name, final Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public static User.UserBuilder builder() {
        return new User.UserBuilder();
    }

    public static class UserBuilder {
        private Long id;
        private String name;
        private Integer age;

        UserBuilder() {
        }

        public User.UserBuilder id(final Long id) {
            this.id = id;
            return this;
        }

        public User.UserBuilder name(final String name) {
            this.name = name;
            return this;
        }

        public User.UserBuilder age(final Integer age) {
            this.age = age;
            return this;
        }

        public User build() {
            return new User(this.id, this.name, this.age);
        }
    }
}

果然如此,UserBuilder.build()方法就是利用這個建構函式來生成的。

結局

最終解決方案就是給User類加上無參的建構函式就OK了,如下:

@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer age;
    private String name;
    private Long id;
}

欄位順序隨便放,最後再執行一下:

User(age=2, name=3, id=1)
User(age=3, name=hhhh, id=2)

相關文章