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>