MyBatis(一) —— jdbcType

什么时候必须加上 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 的对应关系

jdbcTypejavaType
CHARString
VARCHARString
LONGVARCHARString
NUMERICjava.math.BigDecimal
DECIMALjava.math.BigDecimal
BITboolean
BOOLEANboolean
TINYINTbyte
SMALLINTshort
INTEGERint
BIGINTlong
REALfloat
FLOATdouble
DOUBLEdouble
BINARYbyte[]
VARBINARYbyte[]
LONGVARBINARYbyte[]
DATEjava.sql.Date
TIMEjava.sql.Time
TIMESTAMPjava.sql.Timestamp
CLOBClob
BLOBBlob
ARRAYArray
OTHER
UNDEFINED
NVARCHAR
NCHAR
NCLOB
CURSOR
NULL

如有错误,欢迎指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员X小鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值