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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix