集团站切换校区

验证码已发送,请查收短信

复制成功
微信号:togogoi
添加微信好友, 详细了解课程
已复制成功,如果自动跳转微信失败,请前往微信添加好友
打开微信
图标

学习文章

当前位置:首页 > >学习文章 > >

{MyBatyis}动态sql之if choose

发布时间: 2018-09-19 23:12:38

if:

就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。

​List<Stu> getAll(Stu stu);


<select id="getAll" resultType="net.togogo.bean.Stu">

   select * from t_stu where 1=1

   <if test="name!=null">

       and name = #{name}

   </if>

</select>


@Test

public void selectAll(){

   SqlSession session = sessionFactory.openSession();

   Stu stu = new Stu();

   stu.setName("刘备");

   List<Stu> stus =

session.selectList("net.togogo.mapper.StuMapper.getAll",stu);

   stus.stream().forEach(System.out::println);

   session.close();

}

如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了。


choose:

​元素的作用就相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常都是与when和otherwise搭配的。

​List<Stu> getChoose(Stu stu);


<select id="getChoose" resultType="net.togogo.bean.Stu">

   select * from t_stu where 1=1

   <choose>

       <when test="name!=null">

           and name= #{name}

       </when>

       <when test="id!=0">

           and id = #{id}

       </when>

       <otherwise>

           and name = "程咬金"

       </otherwise>

   </choose>

</select>

@Test

public void getChoose(){

   SqlSession session = sessionFactory.openSession();

   Stu stu = new Stu();

   stu.setName("刘备");

   List<Stu> stus =

session.selectList("net.togogo.mapper.StuMapper.getChoose",stu);

   stus.stream().forEach(System.out::println);

   session.close();

}

​when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时候,就会跳出choose,即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的内容。所以上述语句的意思非常简单, 当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and

content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。




上一篇: {HCNA-AI 数学知识}之线性代数实验

下一篇: {HCNA-AI 数学知识}之基础数学实验

十五年老品牌
微信咨询:togogoi 咨询电话:18922156670 咨询网站客服:在线客服

相关课程推荐

在线咨询 ×

您好,请问有什么可以帮您?我们将竭诚提供最优质服务!