mybatis中如何插入null呢?

欣喜 MyBatis 发布时间:2025-04-27 17:42:06 阅读数:16947 1
下文笔者讲述mybatis中插入null值的方法及示例分享,如下所示

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>
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/MyBatis/202504/8451.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者