黑龙江省建设局网站首页/市场调研分析
文章目录
- 8.1动态SQL中的元素
- 8.2 if元素
- 8.3 choose,when,otherwise元素
- 8.4 where,trim元素
- 8.5 set元素
- 8.6 foreach元素
- 8.7 bind元素
8.1动态SQL中的元素
动态Sql是MyBatis的强大特性之一,MyBatis3采用了功能强大的基于OGNL的表达式来完成动态SQL,它消除了之前版本中需要了解的大多数元素,使用不到原来一半的元素就能完成所需工作。
8.2 if元素
在MyBatis中,元素是最常用的判断语句,它类似于Java中的if语句,主要用于实现某些简单的条件选择。
<select id="getRole" parameterType="java.lang.String" resultType="sysRole" >select * from role where 1=1 <!-- r_name参数不等于空,测采取对r_name模糊查询 --><if test="r_name !=null and r_name !='' ">and r_name like concat('%', #{r_name} ,'%')</if></select>
8.3 choose,when,otherwise元素
SELECT * FROM TNotific
<where><choose><when test="method != null">and Method = #{method,jdbcType=VARCHAR}</when><when test="statusOfread != null">and StatusOfread = #{statusOfread,jdbcType=VARCHAR}</when><otherwise>and BizCaseId = #{bizCaseId,jdbcType=VARCHAR}</otherwise></choose>
</where>
8.4 where,trim元素
where标记的作用类似于动态sql中的set标记,他的作用主要是用来简化sql语句中where条件判断的书写的,如下所示
<select id="selectByParams" parameterType="map" resultType="user">select * from user<where><if test="id != null ">id=#{id}</if><if test="name != null and name.length()>0" >and name=#{name}</if><if test="gender != null and gender.length()>0">and gender = #{gender}</if></where></select>
trim标记是一个格式化的标记,可以完成set或者是where标记的功能,如下代码:
<trim prefix="WHERE" prefixoverride="AND |OR"><if test="name != null and name.length()>0"> AND name=#{name}</if><if test="gender != null and gender.length()>0"> AND gender=#{gender}</if></trim>
8.5 set元素
set标记是mybatis提供的一个智能标记,我一般将其用在修改的sql中,例如以下情况
<update>update user <set><if test="name != null and name.length()>0">name = #{name},</if><if test="gender != null and gender.length()>0">gender = #{gender},</if></set>where id = #{id}</update>
8.6 foreach元素
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。
<!--List:forech中的collection属性类型是List,collection的值必须是:list,item的值可以随意,Dao接口中参数名字随意 --><select id="getEmployeesListParams" resultType="Employees">select *from EMPLOYEES ewhere e.EMPLOYEE_ID in<foreach collection="list" item="employeeId" index="index"open="(" close=")" separator=",">#{employeeId}</foreach></select>
8.7 bind元素
mybatis中使用mysql的模糊查询字符串拼接(like) 中涉及到bind的使用
<select id="getEmpsTestInnerParameter" resultType="com.hand.mybatis.bean.Employee"><!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 --><bind name="bindeName" value="'%'+eName+'%'"/> eName是employee中一个属性值SELECT * FROM emp <if test="_parameter!=null">where ename like #{bindeName}</if></select>