使用mybatis对mysql数据库进行增删改查时,如果传递的参数存在空值,那么会报空值异常:
select * from user where 1= 1 and
<if test="params.userCode!= null and params.userCode.trim()!='' ">
and userCode= #{params.userCode}
</if>
<if test="params.name!= null and params.name.trim()!='' ">
and name like "%"#{params.name}"%"
</if>
Exception in thread "main" org.springframework.jdbc.UncategorizedSQLException: Error setting null for parameter #2 with JdbcType OTHER . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property
但是在pl/sql不会提示错误,主要原因是mybatis无法进行转换。所以mybatis在插入空值时,需要指定JdbcType :
select * from user where 1= 1 and
<if test="params.userCode!= null and params.userCode.trim()!='' ">
and userCode= #{params.userCode,jdbcType = VARCHAR}
</if>
<if test="params.name!= null and params.name.trim()!='' ">
and name like "%"#{params.name,jdbcType = VARCHAR}"%"
</if>
javaType和jdbcType的对应关系如下:
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