Mybatis 动态SQL(set)

本文介绍了如何在MyBatis中通过XML映射文件和Java接口实现对特定条件下(如username非空)更新UserInfo表中某一行数据的方法,以及如何在SpringBootTest中进行单元测试。
摘要由CSDN通过智能技术生成

我们先用XML的方式实现 : 把 id 为 13 的那一行的 username 改为 ip

创建一个接口 UserInfo2Mapper ,然后在接口中声明该方法

package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface UserInfo2Mapper {
  
    Integer updateByCondition(UserInfo userInfo);
}

然后在resources 中创建 Userinfo2XMLMapper.xml 文件,然后输入如下代码

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mybatisdemo.mapper.UserInfo2Mapper">
    <update id="updateByCondition">
        update userinfo
        set
        <trim suffixOverrides=",">//删掉最后的逗号
            <if test="username!=null">
                username = #{username},
            </if>
            <if test="age!=null">
                age = #{age},
            </if>
            <if test="gender!=null">
                gender = #{gender}
            </if>
        </trim>
        where id = 13
    </update>
</mapper>

然后我们回到接口 UserInfo2Mapper,右键,Generate,test,勾选 updateByCondition,ok

补充代码,

package com.example.mybatisdemo.mapper;

import com.example.mybatisdemo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

@Slf4j
@SpringBootTest
class UserInfo2MapperTest {
    @Autowired
    private UserInfo2Mapper userInfo2Mapper;

    @Test
    void updateByCondition() {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("ip");
        //userInfo.setAge(23);
        //userInfo.setGender(0);
        userInfo2Mapper.updateByCondition(userInfo);
    }
}

运行成功

 打开数据库看,没毛病

Userinfo2XMLMapper.xml 里面的 trim 标签也可以化简,如下图,其他的跟上面一样,也是可以正常运行的

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mybatisdemo.mapper.UserInfo2Mapper">
    <update id="updateByCondition">
        update userinfo
        <set>
            <if test="username!=null">
                username = #{username},
            </if>
            <if test="age!=null">
                age = #{age},
            </if>
            <if test="gender!=null">
                gender = #{gender}
            </if>
        </set>
        where id = 12
    </update>
</mapper>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值