什么时候必须加上 jdbcType
在 coding 的时候,有时候会发现,比如在 User.xml 中,不管是用 userId = #{userId} 还是 userId = #{userId, jdbcType = Integer},都没有问题。但是什么时候必须要加上 jdbcType 呢?
Mybatis 的官方文档是这样描述 jdbcType 的 :
The JDBC Type from the list of supported types that follows this table. The JDBC type is only required for nullable columns upon insert, update or delete. This is a JDBC requirement, not a MyBatis one. So even if you were coding JDBC directly, you’d need to specify this type – but only for nullable values.
意思是说,只有当将一个空值作用于插入、更新、删除操作时,jdbcType 才是必须的。这是 JDBC 的一个需求,并不是 MyBatis 的。所以即使你是直接编写 JDBC,当它是空的时候,你也一定要指定它的类型,其他情况不需要指定它的类型。
在 Stack Overflow 上,同样有这样的解释:
Most of the times you don’t need to specify the jdbcType as MyBatis is smart enough to figure out the type from the objects you are working with. But if you send your parameters to the MyBatis statement inside a HashMap, for example, and one of the parameters is null, MyBatis won’t be able to determine the type of the parameter by looking at the HashMap because the HashMap is just a generic container and null itself carries no type information. At that point it would be o good idea to provide the jdbcType so that switching the database implementation later on does not cause any issues with null values.
就是说,在大部分时候,我们不需要指定 jdbcType,因为 MyBatis 足够智能地可以辨别出对象的类型。但是如果你传过来的参数是一个 HashMap,其中一个参数是空的,MyBatis 将不能通过 HashMap 来决定对象的类型。因为 HashMap 是一个通用的容器并且如果它本身是空的话,将不会携带任何的类型信息。所以最好的做法是,当值是空的时候去指定它的 jdbcType,这样在之后转换为 db 实现的时候就不会再引起任何问题了。
jdbcType 和 javaType 的对应关系
jdbcType | javaType |
---|---|
CHAR | String |
VARCHAR | String |
LONGVARCHAR | String |
NUMERIC | java.math.BigDecimal |
DECIMAL | java.math.BigDecimal |
BIT | boolean |
BOOLEAN | boolean |
TINYINT | byte |
SMALLINT | short |
INTEGER | int |
BIGINT | long |
REAL | float |
FLOAT | double |
DOUBLE | double |
BINARY | byte[] |
VARBINARY | byte[] |
LONGVARBINARY | byte[] |
DATE | java.sql.Date |
TIME | java.sql.Time |
TIMESTAMP | java.sql.Timestamp |
CLOB | Clob |
BLOB | Blob |
ARRAY | Array |
OTHER | |
UNDEFINED | |
NVARCHAR | |
NCHAR | |
NCLOB | |
CURSOR | |
NULL |
如有错误,欢迎指正。