我们先用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>