< trim prefixOverrides=“and”>:避免【当输入的值只有最后一个(此处指只查age)】,SQL语句前面会多一个and的情况
问题:
一个参数都不给,就会多一个where
如果把where放进trim标签里,那【删除最前面的and】的需求就无法实现
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.example.demo.mapper.UserinfoMapper"><selectid="select"resultType="com.example.demo.model.UserInfo">
select * from userinfo
where
<trimprefixOverrides="and"><iftest="username!=null">
username = #{username}
</if><iftest="password!=null">
and password = #{password}
</if><iftest="age!=null">
and age = #{age}
</if></trim></select></mapper>
方式二:使用where 1=1:
where 1=1:当搜寻条件一个都没有时,相当于【查询所有】
and username = #{username}:相比于方式一,第一个搜寻条件需要加上and
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.example.demo.mapper.UserinfoMapper"><selectid="select"resultType="com.example.demo.model.UserInfo">
select * from userinfo
where 1=1
<trimprefixOverrides="and"><iftest="username!=null">
and username = #{username}
</if><iftest="password!=null">
and password = #{password}
</if><iftest="age!=null">
and age = #{age}
</if></trim></select></mapper>
方式三:使用where标签:该标签由Mybatis提供
where标签的作用:
当查询条件都为空时,where标签会自动去除where关键字
当只查询最后一个条件时,可以帮我们去除最前面的 and字符
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.example.demo.mapper.UserinfoMapper"><selectid="select"resultType="com.example.demo.model.UserInfo">
select * from userinfo
<where><iftest="username!=null">
username = #{username}
</if><iftest="password!=null">
and password = #{password}
</if><iftest="age!=null">
and age = #{age}
</if></where></select></mapper>
3.4 更新场景 set标签
写法一:set + trim:
直接用set + 用trim标签去除最后一个逗号
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.example.demo.mapper.UserinfoMapper"><updateid="update">
update userinfo
set
<trimsuffixOverrides=","><iftest="username != null">
username = #{username},
</if><iftest="age != null">
age = #{age},
</if><iftest="gender != null">
gender = #{gender}
</if></trim>
where age = 21
</update></mapper>