您的位置:首页 > 数据库

Mybatis动态SQL

2016-11-18 11:31 309 查看
可以根据传人的SQL参数不同,生成不同的SQL语句

MyBatis提供了一套标签,用于在XML中动态拼凑SQL语句

select * from emp
<if test="xxx">...</if>

<chose>
<when test="xxx">...</when>
<when test="xxx">...</when>
<otherwise>...</otherwise>
</choose>

<foreach></foreach>
<where>
<set>


组合查询功能

a.笔记:标题,状态,开始日期,结束日期

根据上述条件,用户可以随意输入信息,按信息搜索

<!-- 组合查询 -->
<select id="hightSearch" parameterType="map" resultType="org.tarena.note.entity.Note">
select
cn_note_id,
cn_note_title,
cn_note_create_time
from cn_note
<where>
<if test="title!=null">
cn_note_title like #{title}
</if>
<if test="status!=null">
and cn_note_status_id = #{status}
</if>
<if test="beginDate!=null">
and cn_note_create_time >= #{beginDate}
</if>
<if test="endDate!=null">
and cn_note_create_time <= #{endDate}
</if>
</where>
</select>


b.懂爱更新SQL

笔记标题,创建时间,所属笔记本。ajax将这三值传入

如果3值不为空,则update传入

<!-- 动态更新,将一些不为null的属性更新到数据库 -->
<update id="dynamicUpdate" parameterType="org.tarena.note.entity.Note">
update cn_note
<set>
<if test="cn_notebook_id != null">
cn_notebook_id = #{cn_notebook_id},
</if>
<if test="cn_user_id != null">
cn_user_id = #{cn_user_id},
</if>
<if test="cn_note_status_id != null">
cn_note_status_id = #{cn_note_status_id},
</if>
<if test="cn_note_type_id != null">
cn_note_type_id = #{cn_note_type_id},
</if>
<if test="cn_note_title != null">
cn_note_title = #{cn_note_title},
</if>
<if test="cn_note_body != null">
cn_note_body = #{cn_note_body},
</if>
<if test="cn_note_create_time != null">
cn_note_create_time = #{cn_note_create_time},
</if>
<if test="cn_note_last_modify_time != null">
cn_note_last_modify_time = #{cn_note_last_modify_time}
</if>
</set>
where
cn_note_id = #{cn_note_id}
</update>


c.批量删除

delete from cn_note where cn_note_id = ?

<delete id="deleteNotes">
delete from cn_note
where cn_note_id in
<foreach collection="array" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis 动态sql