Java MyBatis动态SQL查询(单条件&多条件)
Java MyBatis动态SQL查询(单条件&多条件)
·
根据上一章节我们讲到,用户在实际使用的时候,不会根据你有几个input而去填写,也许只填写一个,或者两个,就执行操作了,这时候我们就需要讲到MyBatis动态SQL查询
多条件(if与where)
只需要修改xml配置文件即可
if:用于判断参数是否有值,使用test属性进行条件判断
*存在问题:第一个条件不需要逻辑运算符 and
*解决方案:
(1):在where后面加上恒等式,使所有的条件格式都一样
(2):在所有条件都一样的基础上,使用mybatis自带的where标签(推荐)
(1):在where后面加上恒等式,使所有的条件格式都一样
<select id="selectByCondition" resultType="com.itheima.pojo.Brand" resultMap="brandResultMap">
select * from tb_brand
where 1=1
<if test="status != null">
and status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != ''">
and brand_name like #{brandName}
</if>
</select>
(2):在所有条件都一样的基础上,使用mybatis自带的where标签(推荐)
<select id="selectByCondition" resultType="com.itheima.pojo.Brand" resultMap="brandResultMap">
select * from tb_brand
/*where 1=1*/
<where>
<if test="status != null">
and status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != ''">
and brand_name like #{brandName}
</if>
</where>
</select>
单条件
(条件是不固定的,也就是在多个条件中选择一个)
从多个条件中选择一个
*choose(when,otherwise)选择,相当于Java语句中的switch语句
问题:如果用户一个条件也没有选择怎么办
1.使用otherwise来进行保底
2.使用mybatis自带的<where>标签
1.使用otherwise来进行保底
<!-- 单条件的动态查询 -->
<select id="selectByConditionSingle" resultMap="brandResultMap">
select * from tb_brand
where
<choose><!--相当于switch-->
<when test="status != null"><!--相当于case-->
status = #{status}
</when><!--相当于case-->
<when test="companyName != null and companyName != ''"><!--相当于case-->
company_name like #{companyName}
</when>
<when test="brandName != null and brandName != ''"><!--相当于case-->
brand_name like #{brandName}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</select>
2.使用mybatis自带的<where>标签
<!-- 单条件的动态查询 -->
<select id="selectByConditionSingle" resultMap="brandResultMap">
select * from tb_brand
<where>
<choose><!--相当于switch-->
<when test="status != null"><!--相当于case-->
status = #{status}
</when><!--相当于case-->
<when test="companyName != null and companyName != ''"><!--相当于case-->
company_name like #{companyName}
</when>
<when test="brandName != null and brandName != ''"><!--相当于case-->
brand_name like #{brandName}
</when>
</choose>
</where>
</select>
</mapper>
总结:思想不要太固执,这个东西还得慢慢来
更多推荐
已为社区贡献9条内容
所有评论(0)