?结合上个博客一起看哦
上篇博客我们说.用户在表中插入数据的时候,有的数据可能不想插入,我们就需要设置,当用户插入这个字段的数据的时候就显示,不插入的话就为null,比如性别不想插入,那么 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">
<insert id="insertByXML">
insert into userinfo(username,password,age,
<if test="gender!=null">
gender,
</if>
phone)
values(#{username},#{password},#{age},
<if test="gender!=null">
#{gender},
</if>
#{phone})
</insert>
</mapper>
那如果每个字段都像性别那样设置,代码该如何去写呢,以此类推大概是下面这样的写法
<?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">
<insert id="insertByXML">
insert into userinfo(
<if test="username!=null">
username,
</if>
<if test="password!=null">
password,
</if>
<if test="username!=null">
age,
</if>
<if test="gender!=null">
gender,
</if>
<if test="phone!=null">
phone
</if>
)
values(
<if test="username!=null">
#{username},
</if>
<if test="password!=null">
#{password},
</if>
<if test="age!=null">
#{age},
</if>
<if test="gender!=null">
#{gender},
</if>
<if test="phone!=null">
#{phone}
</if>
)
</insert>
</mapper>
?按理来说是上面这样写,但是插入数据的时候,假如有两个字段没插入数据,那就会因为逗号的问题报错.比如 gender 和 phone 都没插入数据,那么 age 就成了最后的数据,age 后面跟着逗号就不行
具体错误的日志我这里就不展示了,接下来我们说怎么解决逗号的问题
所以我们需要引入 trim标签 帮我们解决逗号问题
把 trim 标签给加上?,我们把括号也交给 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">
<insert id="insertByXML">
insert into userinfo
<trim suffixOverrides="," prefix="(" suffix=")">
<if test="username!=null">
username,
</if>
<if test="password!=null">
password,
</if>
<if test="age!=null">
age,
</if>
<if test="gender!=null">
gender,
</if>
<if test="phone!=null">
phone
</if>
</trim>
values(
<trim suffixOverrides=",">
<if test="username!=null">
#{username},
</if>
<if test="password!=null">
#{password},
</if>
<if test="age!=null">
#{age},
</if>
<if test="gender!=null">
#{gender},
</if>
<if test="phone!=null">
#{phone}
</if>
</trim>
)
</insert>
</mapper>
?然后我们试试只添加三个字段的数据
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class UserInfo2MapperTest {
@Autowired
private UserInfo2Mapper userInfo2Mapper;
@Test
void insertByXML() {
UserInfo userInfo = new UserInfo();
userInfo.setUsername("ppp");
userInfo.setPassword("555www");
userInfo.setAge(23);
//userInfo.setGender(1);
//userInfo.setPhone("177966");
userInfo2Mapper.insertByXML(userInfo);
}
}
?没问题