【Mybatis】——動態sql

開篇

mybatis的核心是對sql的靈活操作,所以在mapper.xml中對sql的動態拼接是必不可少的功能。

正文

sql拼接實例


優化

上圖中相同的sql拼接代碼可能會被其他的statement使用,爲了將這些相同的代碼進行抽取,mybatis中使用了sql片段的概念。

 

sql片段

sql片段的定義

<!-- 定義sql片段
id:sql片段的唯 一標識
 
經驗:是基於單表來定義sql片段,這樣話這個sql片段可重用性才高
在sql片段中不要包括 where
 -->
<sql id="query_user_where">
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username LIKE '%${userCustom.username}%'
</if>
</if>
</sql>


sql片段調用

<select id="findUserList" parameterType="cn.itcast.mybatis.po.UserQueryVo"
resultType="cn.itcast.mybatis.po.UserCustom">
SELECT * FROM USER
<!--
where可以自動去掉條件中的第一個and
 -->
<where>
<!-- 引用sql片段 的id,如果refid指定的id不在本mapper文件中,需要前邊加namespace -->
<include refid="query_user_where"></include>
<!-- 在這裏還要引用其它的sql片段  -->
</where>
</select>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章