mybatis添加空值
我们添加数值时可能是空值,如果我们不做处理,那么在数据库中存储的将是"" 空字符串,如果有重复约束将会导致下一次插入数据失败,那么该如何解决这个问题呢?
- 在对象赋值不完整的字段后添加 jdbcType 如:
<insert id="addAcc" parameterType="com.by.tsgl.bean.User">
insert into user
(user_id,user_account,user_email,user_tel,user_pwd,user_name,user_sex,user_id_number)
values
(#{user_id},#{account},#{user_email,jdbcType=VARCHAR},#{user_tel, jdbcType=CHAR},#{password},#{username, jdbcType=VARCHAR},#{user_sex,jdbcType=TINYINT},#{user_id_number,jdbcType=CHAR})
</insert>
- 然后在 mybatis-config.xml 中添加配置
<settings>
<setting name="jdbcTypeForNull" value="NULL" />
</settings>
- 如若是其它类型也可使用 标签
<if test="otherType != null and otherType!= ''" >
otherType = #{otherType}
</if>
测试:
postman数据
{
"user_id":10,
"account" : "10316081",
"password":"123456",
"username":null,
"user_email": "",
"user_tel":"",
"user_sex":"",
"user_id_number":""
}
看到数据库中 只有username显示为null,其他均为空白(空白的空值如果设置了不可重复的约束,那么再次插入会出错!)
使数据库中插入null值的请求json修改意见:
-
当我们将
""
改为null后,插入值为正确。{ "user_id":10, "account" : "10316081", "password":"123456", "username":null, "user_email": "", "user_tel":"", "user_sex":"", "user_id_number":"}
-
我们直接将为空值的 key-value对 全部删除
-
{ "user_id":10, "account" : "1016081", "password":"123456" //空值的字段全部不要也可以正确插入数据 }
-
这种方式也可以使数据库中对应字段为null
-