Mybatis中什麼時候應該聲明jdbcType

疑問來自於,有時候Mapper.xml中

pid = #{pid,jdbcType=INTEGER}

pid = #{pid}

都可以用


那麼問題來了,


Mybatis中什麼時候應該聲明jdbcType?

當Mybatis不能自動識別你傳入對象的類型時。


什麼情況下,Mybatis不能自動識別我的傳入類型?

例如:當你傳入空值的時候。


簡而言之,加上肯定不會報錯。


來源:Is jdbcType necessary in a MyBatis mapper?

引用:

As you mentioned yourself, you need to specify the jdbcType when passing null values for parameters.

Some databases need to know the value's type even if the value itself is NULL. For this reason, for maximum portability, it's the JDBC specification itself that requires the type to be specified and MyBatis needs to pass it along since it's build on top of JDBC.

From the MyBatis documentation:

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.

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.


PS:要慢慢習慣看文檔,直接google像吃快餐,不能一直吃!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章