choose元素
choose元素也可说是对它的属性做或(or)操作,当我们列出三个when表达式时,它会从第一个when开始判断,如果为真则直接结束choose元素。也就是说它的三个when最多只会执行一条,而如果都为假则执行otherwise属性中的sql语句。相对做与(and)操作,只要条件为真就执行的if标签相比,他显得更加灵活。
演示:
CM1.xml(一个mapper)
<mapper namespace="com.itheima.mapper.CM1">
<select id="C" parameterType="com.itheima.po.Account" resultType="com.itheima.po.Account">
select * from account where 1=1
<choose>
<when test="username != null and username != '' ">
and username like concat('%',#{username},'%')
when>
<when test="balance != null and balance > 0">
and balance > #{balance}
when>
<when test="id != null and id > 0">
and id = #{id}
when>
<otherwise>
and id=4
otherwise>
choose>
select>
mapper>
基础的SQL语句:
select * from account where 1=1
< when test="username != null and username != ‘’ " >
如果用户名(username)不为空的话,SQL语句为:
select * from account where 1=1 and username like concat('%',#{username},'%')
拼接完成后直接退出choose标签,不再执行下面的when
< when test=“balance != null and balance > 0”>
如果第一个when不成立,而且balance(余额)也不为空且大于0的话,SQL语句为:
select * from account where 1=1 and balance > #{balance}
拼接完成后直接退出choose标签,不再执行下面的when
如果前两个when条件不成立,最后一个when条件成立的话,SQL语句拼接为:
select * from account where 1=1 and id=#{id}
如果以上所有的when皆不执行的话,拼接otherwise标签中的sql语句:
select * from account where 1=1 and id=4
至此sql语句拼接完成。
测试方法:
@Test
public void chooseTest() throws Exception {
SqlSession session=MyBatisUtils.getSqlSession();//获取会话
Account account=new Account();//账户类 只有这三个属性
account.setId(1);
account.setUsername("小明");
account.setBalance(8000);
List<Account> users=session.selectList("com.itheima.mapper.CM1.C", account);
session.close();//关闭会话
for(Account a:users) {
System.out.println(a.toString());
}
}
当三个when都给定了数据时,是否会先判断ID呢?
不会的,它会先判断username是否有效,来看结果
实践发现,当第所有when条件满足时,只会拼接第一个when条件中的sql语句。
再试下注释掉username
……其他代码
account.setId(1);
//account.setUsername("小明");
account.setBalance(8000);
……
结果
是了,结果没错。它拼接了第二个when,但是为什么没有结果显示呢?
应为我们的sql语句写的是大于8000的账户,您往上翻数据表。看看有无?
再试下注释掉username和balance
……其他代码
account.setId(1);
//account.setUsername("小明");
//account.setBalance(8000);
……
结果
结果如我所愿,执行了最后一个when
再试下注释掉所有数据
……其他代码
//account.setId(1);
//account.setUsername("小明");
//account.setBalance(8000);
……
结果
所有when条件不成立,所以拼接了otherwise标签中的sql,结果正确。
好了,能力有限,choose元素就实践到此。
MyBatis动态SQL中的一些元素 if、set、trim、choose、foreach、bind