背景
MyBatis是一款优秀的orm框架,封装了一些列的最基本crud操作方法
多条件查询
相比于原生的JDBC操作数据,通过MyBatis解决了不少我们开发中的硬编码问题!
在我们平常使用的时候,会出现多条件查询的情况,为了适应这种情况,我们便出现了多条件查询,作为一款优秀的orm框架——MyBatis自然是支持的。
其实,实现多条件查询的方式就是Mybatis的特色——动态SQL
动态sql
因为采用的是Mapper代理方式开发,我们可以通过xml来实现我们的sql语句,动态SQL再这里体现的淋漓尽致,下面我们看一下我们平常用到的xml配置,如下所示:
<!-- 根据用户名模糊查询,根据权限查询 -->
<select id="select" resultMap="userinfoMap" parameterType="java.util.Map">
<!-- 用include标签引入sql片段,refid写定义sql片段的id,where标签不要写在片段里 -->
select <include refid="zd"/> from userinfo
<!-- 当页面没有输入用户名和选择权限,就让它的条件永远为真,就变成全查询了 -->
<where>
<if test="username == null and username = '' and upower == -1">
and 1=1
</if>
<if test="username != null and username !=''">
and username LIKE '%${username}%'
</if>
<if test="upower != -1">
and upower=#{upower}
</if>
</where>
</select>
where 标签配合if,自动帮我们过滤掉了不需要的sql条件,我们从条件中可以看到为null和''的值都被过滤掉了,这是牛的设计!
Mybatis中海油一种语法是——多条件中选择一个条件查询的场景,利用分之前到可以实现条件的选择
这里有点像switch……case语法,choose相当于switch,when相当于case,otherwise相当于default,当着里面没有匹配上,则选择otherwise执行
<select id="selByCondition" resultMap="userinfoMap">
select *
from userinfo where
<choose>
<when test="status !=null">
STATUS=#{STATUS}
</when>
<when test="companyName !=null and companyName !=''">
company_name like #{companyName}
</when>
<when test="bracdName !=null and bracdName !=''">
bracd_name like #{bracdName}
</when>
<otherwise>1=1</otherwise>
</choose>
</select>
好了,今天的Mybatis讲到这,欢迎大家留言交流,也欢迎大家关注我的工 种 昊《coder练习生》
这篇文章因为文字段被标记为质量低,以下文字就是为了打破它的文字段而造成的质量低!
相信和我一样遇到这个问题的的小伙伴们,心里也已经暗自问候了这个产品经理的祖总十八代了吧!
算法实在是不敢苟同,文字的长短和文章的质量有毛线的关系吗?