mybatis Sql动态问题集合
where 和 if 搭配:
where 其实就是表示sql语句中 where的用法;
where包围后,就不用在sql语句中加where了;
if语句的语法结构:<if test="" ></if> 其中的test就是判断语句。""写语法;
<mapper namespace="com.example.demo.mapper.DeptMapper">
<select id="selectAll" parameterType="List" resultType="com.example.demo.entity.Dept">
select * from dept
<where>
1=1
<if test="id!=null">
and id=#{id}
</if>
<if test="name!=null">
or name=#{name}
</if>
</where>
</select>
</mapper>
4.choose(when,otherwise) 语句
有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句
<select id="selectIf" parameterType="List" resultType="com.example.demo.entity.Dept">
select * from dept
<where>
<choose>
<when test="id !='' and id != null">
id=#{id}
</when>
<when test="name !='' and name != null">
and name=#{name}
</when>
<otherwise>
and location=#{location}
</otherwise>
</choose>
</where>
</select>
也就是说,这里我们有三个条件,id,name,location,只能选择一个作为查询条件
如果 id 不为空,那么查询语句为:select * from user where id=?
如果 id 为空,那么看name 是否为空,如果不为空,那么语句为 select * from user where name=?;
如果 name 为空,那么查询语句为 select * from user where location=?
批量删除
//可以用@parame注解改变 collection的名称,里面数组默认名称为集合array
//foreach里面有个分隔符separator;
<delete id="DeleteAllMapper">
delete from edu_teacher
<where>
<if test="id!=null and id.size>0">
<foreach collection="id" item="id" open="id in(" separator="," close=")">
#{id}
</foreach>
</if>
</where>
</delete>

浙公网安备 33010602011771号