序言
MyBatis,大家都知道,半自动的ORM框架,原来叫ibatis,后来好像是10年apache软件基金组织把它托管给了goole code,就重新命名了MyBatis,功能相对以前更强大了。它相对全自动的持久层框架hibernate,更加灵活,更轻量级,这点我还是深有体会的。
MyBatis的一个强大特性之一就是动态SQL能力了,能省去我们很多串联判断拼接SQL的痛苦,根据项目而定,在一定的场合下使用,能大大减少程序的代码量和复杂程度,不过还是不是过度太过复杂的使用,以免不利于后期的维护和扩展。
下边就简单介绍一下吧。
介绍
foreach 批量处理
<foreach> 元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素是很智能的,它不会偶然地附加多余的分隔符。注意:你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。当你这么做的时候,MyBatis 会自动将它包装在一个Map 中,用名称在作为键。List 实例将会以“list”作为键,而数组实例将会以“array”作为键。最常用在批量删除和批量插入功能上,如下:
-
- <delete id="batchDelete">
- delete from test where id in
- <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </delete>
-
- <insert id="batchInsert">
- insert into test (id, name, year,birthday) values
- <foreach collection="list" item="item" index="index" separator=",">
- (#{id}, #{name},#{year},#{birthday,jdbcType=DATE})
- </foreach>
- </insert>
if经常判空使用
-
- <update id="update" parameterType="com.inspur.demo.po.ExampleBean" >
- update test set name=#{name},year=to_number(#{year}),birthday=to_date(#{birthday},'yyyy-mm-dd hh24:mi:ss')
- <if test="id!=null">
- where id = #{id}
- </if>
- </update>
where set的使用
<where> 元素知道如果由被包含的标记返回任意内容,就仅仅插入“WHERE” 。而且,如果以“AND”或“OR”开头的内容,那么就会跳过 WHERE 不插入。
- <where>
- <if test="id!= null">
- m.id=#{id}
- </if>
- <if test="name!= null">
- and m.name like '%${name}%'
- </if>
- <if test="year!= null">
- and m.year=#{year,jdbcType=INTEGER}
- </if>
- <if test="birthday!= null">
- <![CDATA[and to_char(m.birthday,'yyyy-MM-dd') < #{birthday}]]>
- </if>
- </where>
<set> 元素可以被用于动态包含更新的列,而不包含不需更新的。
-
- lt;update id="update" parameterType="com.inspur.demo.po.ExampleBean" >
- update test
- <set>
- <if test="name!= null">name=#{name},</if>
- <if test="year!= null">year=#{year,jdbcType=INTEGER},</if>
- <if test="birthday!= null">birthday=#{birthday,jdbcType=DATE}</if>
- </set>
- <if test="id=!null" >
- where id=#{id}
- </if>
- lt;/update>
choose when的使用(相对来说用的少)
-
- <select id="getByBean" parameterType="com.inspur.demo.po.ExampleBean" resultType="map">
- select m.* from test m where 1=1
- <choose>
- <when test="判断1">
- and 条件1
- </when>
- <when test="判断2">
- and 条件2
- </when>
- <otherwise>
- and 条件3
- </otherwise>
- </choose>
- </select>
转载请注明—作者:Java我人生(陈磊兴) 原文出处:http://blog.csdn.net/chenleixing/article/details/43818227