Mybatis框架篇章十
【摘要】 单条件查询如果我只给出任意一个条件,当然上面的模式是完全可以满足的。我们只是来说明一下满足一个单条件查询的语法。明着说就像switch case语句一样。我们只在sql映射文件中做出说明更改的部分。其他的还是一样的模式。 <select id="selectByConditionSingle" resultMap="brandResultMap"> select * ...
单条件查询
如果我只给出任意一个条件,当然上面的模式是完全可以满足的。我们只是来说明一下满足一个单条件查询的语法。
明着说就像switch case语句一样。
我们只在sql映射文件中做出说明更改的部分。其他的还是一样的模式。
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
where
# choose相当于switch
# when相当于case
<choose> <!--相当于switch-->
<when test="status!=null">
status = #{status}
</when>
<when test="companyName! = null and companyName != ''">
company_name like {companyName}
</when>
<when test="brandName!=null and brandName != ''">
brand_name like # {brandName}
</when>
</choose>
</select>
这次把方法封装到brand对象了。这样也是可以的。
运行
在单条件查询里面,如果我一个条件都没有写。会发生什么?就上诉的代码段。
这里测试代码这里注释掉了。
如果都满足的话,我们还需要留有余地。不然会出现错误。用otherwise是一种办法
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
where
# choose相当于switch
# when相当于case
<choose> <!--相当于switch-->
<when test="status!=null">
status = #{status}
</when>
<when test="companyName! = null and companyName != ''">
company_name like {companyName}
</when>
<when test="brandName!=null and brandName != ''">
brand_name like # {brandName}
</when>
<otherwise>1=1</otherwise>
</choose>
</select>
这样的话,至少不会报错。如果你没有添加搜索数据的话,就不出现结果就行了。
然后其实我们还是可以用到智能的where标签
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
<where>
# when相当于case
<choose> <!--相当于switch-->
<when test="status!=null">
status = #{status}
</when>
<when test="companyName!= null and companyName != ''">
company_name like #{companyName}
</when>
<when test="brandName!= null and brandName != ''">
brand_name like #{brandName}
</when>
</choose>
</where>
# choose相当于switch
</select>
where标签的智能之处在于可以帮助检查语法的问题。很明显,我让三个条件都没有匹配,然后这个标签会截断后面的语句。
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)