mybatis upsert操作[插入/更新]

这篇博客详细介绍了如何使用SQL语句进行动态插入和更新操作,特别是针对字段值为空的情况,如何智能地决定是否插入或使用默认值。示例代码展示了在`DemoTable`表中,根据`unique_key1`和`unique_key2`的唯一性,执行插入或更新操作,并考虑了`tel_number`和`addr`字段的非空判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    @Insert({"<script>"

            + " INSERT INTO "
            + " DemoTable ("
            + "       unique_key1,"
            + "       unique_key2,"
            + "       stu_name,"
            + "       stu_age,"
            /*判断要插入的该字段的值是否为空,为空则不插入该字段,此时会使用数据库创建时的默认值*/
            + "       <if test='telNumber != null and telNumber.length()>0'> tel_number, </if>" 
            + "       <if test='addr != null and addr.length()>0'> addr, </if>"
            + "       remarks,"
            + "       update_user,"
            + "       update_time"
            + " )"
            + " VALUES ("
            + "       #{uniqueKey1},"
            + "       #{uniqueKey2},"
            + "       #{stuName},"
            + "       #{stuAge},"
            + "       <if test='telNumber != null and telNumber.length()>0'> #{telNumber}, </if>"
            + "       <if test='addr != null and addr.length()>0'> #{addr}, </if>"
            + "       #{remarks},"
            + "       #{updateUser},"
            + "       #{updateTime}"
            + " )"
            + " ON DUPLICATE KEY UPDATE"  /*如果后面的条件成立则UPDATE,不成立则INSERT*/
            + " unique_key1=#{uniqueKey1}," /*条件1*/
            + " unique_key2=#{uniqueKey2}"  /*条件2*/

            + "</script>"})

参考链接:

MySql的upsert操作_data_scientist的博客-优快云博客_upsert into 几种写法

当字段为空时MyBatis添加默认值 - VoidCC

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值