mybatis中如何插入null呢?
下文笔者讲述mybatis中插入null值的方法及示例分享,如下所示
可使用 `<if>` 标签来判断参数是否为空,
并在为空时插入 `NULL`。
例:
可使用 `<choose>`、`<when>` 和 `<otherwise>` 标签。
例:
mybatis插入null值的实现思路
方式1: 直接在sql脚本中插入 null值 方式2: 使用if 标签 判断是否为空 方式3: 使用`choose`,`when`和`otherwise`标签 方式4: 使用`jdbcType`属性例
1.直接在SQL语句中使用`NULL`
如果明确知道某个字段需要插入 `NULL` 值 可直接在 SQL 语句中使用 `NULL`。 例 <insert id="insertUser" parameterType="map"> INSERT INTO users (id, name, email) VALUES ({id}, {name}, NULL) </insert> //`email` 字段将被插入为 `NULL`。
2.使用`if`标签判断参数是否为空
在参数为空时插入 `NULL`,可使用 `<if>` 标签来判断参数是否为空,
并在为空时插入 `NULL`。
例:
<insert id="insertUser" parameterType="map"> INSERT INTO users (id, name, email) VALUES ( {id}, {name}, <if test="email != null"> {email} </if> <if test="email == null"> NULL </if> ) </insert>
3.使用`choose`、`when` 和 `otherwise` 标签
如果逻辑比较复杂可使用 `<choose>`、`<when>` 和 `<otherwise>` 标签。
例:
<insert id="insertUser" parameterType="map"> INSERT INTO users (id, name, email) VALUES ( {id}, {name}, <choose> <when test="email != null"> {email} </when> <otherwise> NULL </otherwise> </choose> ) </insert>
4.使用`jdbcType`属性
有时候,需要显式地指定`jdbcType` 为 `NULL` 特别是在使用 `{param, jdbcType=NULL}` 时。例:
<insert id="insertUser" parameterType="map"> INSERT INTO users (id, name, email) VALUES ( {id}, {name}, <if test="email == null"> {email, jdbcType=NULL} </if> <if test="email != null"> {email} </if> ) </insert>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。