MyBatis學習三:SqlMapConfig.xml屬性和sql片段
SqlMapConfig.xml
1、properties屬性
將資料庫連線引數單獨配置在db.properties中,只需在SqlMapConfig.xml中載入db.properties的屬性值。在SqlMapConfig.xml中就不需要對資料庫連線引數硬編碼。
將資料庫連線引數只配置在db.properties中,原因:方便對引數進行統一管理,其他xml可以引用該db. properties。
注意:MyBatis將按照下面的順序來載入屬性:
在properties元素內定義的屬性首先被讀取;
然後會讀取properties元素中resource或url載入的屬性,它會覆蓋已讀取的同名屬性;
最後讀取parameterType傳遞的屬性,它會覆蓋已讀取的同名屬性。
建議:不要在properties元素體內新增任何屬性值,只將屬性值定義在properties資料夾中。在properties檔案中定義屬性名要有一定的特殊性,如xx.xx.x
2、settings
MyBatis全域性配置引數,全域性配置引數會影響MyBatis的執行行為。不要隨意配置。
3、typeAlias(別名)
在mapper.xml中,定義很多的statement,statement需要parameterType指定輸入引數型別,需要resultType指定輸出結果的對映型別。如果在指定型別時輸入型別全路徑,不方便開發,可針對parameterType 和resultType指定的型別定義一些別名,在mapper.xml中通過別名定義,方便開發。
1)針對單個別名定義(type:型別的路徑,alias:別名):
<typeAlias type=”cn.itcast.mybatis.po.User” alias=”user” />
2)批量別名定義(指定包名,mybatis自動掃描包中的po類,自動定義別名,別名就是類名(首字母大寫或小寫均可)):
<typeAliases>
<package name=”cn.itcast.mybatis.po”/>
</typeAliases>
4、typeHandlers(類處理器)
mybatis中通過typeHandlers完成jdbc型別和java型別的轉換。通常情況,mybatis提供的型別處理器滿足日常需要,不需要自定義。
5、mappers(對映配置)
1)通過resource加裝單個對映檔案
<mapper resource=”mapper/UserMapper.xml”/>
2)通過mapper介面載入
批量載入mapper,指定mapper介面的包名,mybatis自動掃描包下所有mapper介面載入。
遵循一些規範:需要將mapper介面類名和mapper.xml對映檔名稱保持一致,且在一個目錄中。
上邊規範的前提是:使用的是mapper代理方法。
<package name=”cn.itcast.mybatis.mapper”/>
動態sql
Mybatis核心對sql語句進行靈活操作,通過表示式進行判斷,對sql進行靈活拼接、組裝。
1、sql示例
<select id=”findUserList” parameterType=”cn.itcast.mybatis.po.UserQueryVo” resultType=”cn.itcast.mybatis.po.UserCustom”>
SELECT * FROM USER
<!—where可以自動去掉條件中第一個and -->
<where>
<if test=”userCustom!=null”>
<if test=”userCustom.sex!=null and userCustom.sex!=’’”>
and user.sex=#{userCustom.sex}
</if>
<if text=”userCustom.username!=null and userCustom.username!=’’”>
and user.username LIKE ‘%${userCustom.username}%’
</if>
<span> </span></if>
<span> </span></where>
</select>
2、sql片段
定義sql片段:
id:sql片段的唯一標識。
<sql id=”query_user_where”>
<if test=”userCustom!=null”>
<if test=”userCustom.sex!=null and userCustom.sex!=’’”>
and user.sex=#{userCustom.sex}
<if>
<if text=”userCustom.username!=null and userCustom.username!=’’”>
and user.username LIKE ‘%${userCustom.username}%’
</if>
</if>
</sql>
經驗:1)基於表單來定義sql片段,這樣這個sql片段可重用性才高
2)在sql片段中不要包括where
3)引用sql片段的id,如果refid指定的id不在本mapper檔案中,需要前面加namespace
3、foreach
向sql傳遞陣列或list,mybatis使用foreach解析。
在使用者查詢列表和查詢總數的statement中增加多個id輸入查詢。
sql語句如下:
SELEC * FROM USER WHERE id=1 OR id=16
SELEC * FROM USER WHERE id IN(1,10,16)
<sql id="selForeach">
<if test="ids!=null">
<!-- 使用foreach遍歷傳入的集合
collection:指定輸入物件中集合屬性
item:每個遍歷生成物件中
open:開始遍歷時拼接的串
close:結束遍歷時拼接的串
separator:遍歷的兩個物件中需要拼接的串 -->
<!-- 使用實現下邊的sql拼接
AND (id=1 OR id=10 OR id=16) -->
<foreach collection="ids" item="user_id" open="AND (" close=")" separator="OR">
<!-- 每個遍歷需要拼接的串 -->
id=#{user_id}
</foreach>
</if>
</sql>
<select id="selForeach" >
SELECT
<include refid="Base_Column_List"></include>
FROM user
WHERE
<include refid="selForeach"></include>
</select>