一、核心配置文件 SqlMapConfig.xml
-
environments 標簽
數據庫環(huán)境的配置,?持多環(huán)境配置- 事務管理器(transactionManager)類型有兩種
- JDBC:這個配置就是直接使用了JDBC 的提交和回滾設置,它依賴于從數據源得到的連接來管理事務作用域
- MANAGED:這個配置幾乎沒做什么,它從來不提交或回滾?個連接,而是讓容器來管理事務的整個生命周期(比如 JEE 應?服務器的上下文), 默認情況下它會關閉連接,然而?些容器并不希望這樣,因此需要將 closeConnection 屬性設置為 false 來阻止它默認的關閉行為
- 數據源(dataSource)類型有三種:
- UNPOOLED:這個數據源的實現(xiàn)只是每次被請求時打開和關閉連接
- POOLED:這種數據源的實現(xiàn)利用“池”的概念將 JDBC 連接對象組織起來
- JNDI:這個數據源的實現(xiàn)是為了能在如 EJB 或應用服務器這類容器中使用,容器可以集中或在外部配置數據源,然后放置?個 JNDI 上下文的引用
- 事務管理器(transactionManager)類型有兩種
-
mapper 標簽
該標簽的作用是加載映射的,加載方式有如下幾種- 使用相對于類路徑的資源引用
例如:<mapper resource="org/mybatis/builder/AuthorMapper.xml"/> - 使用完全限定資源定位符(URL)
例如:<mapper url="file:///var/mappers/AuthorMapper.xml"/> - 使用映射器接口實現(xiàn)類的完全限定類名
例如:<mapper class="org.mybatis.builder.AuthorMapper"/> - 將包內的映射器接口實現(xiàn)全部注冊為映射器
例如:<package name="org.mybatis.builder"/>
注意:使用該方式批量注冊的時候,需要保證與 mapper 接口同包同名
例如:UserMapper這個接口的接口的所在包是com.wujun.pojo,那么UserMapper.xml文件就得放在resources目錄下的com/wujun/pojo文件夾中
- 使用相對于類路徑的資源引用
-
Properties 標簽
實際開發(fā)中,習慣將數據源的配置信息單獨抽取成?個 properties 文件,該標簽可以加載額外配置的 properties 文件
-
typeAliases 標簽
給實體類的全限定名起別名,方便統(tǒng)一管理使用
mybatis框架已經為我們設置好的?些常用的類型的別名:String -> string;Long -> long;Integer -> int;Double -> double;Boolean -> boolean 等等<typeAliases> <!--給單個實體類的全限定類名起別名--> <typeAlias type="com.wujun.pojo.User" alias="user"></typeAlias> <!--批量起別名:該包下所有類的本身的類名,別名不區(qū)分大小寫--> <package name="com.wujun.pojo"/> </typeAliases> <select id="findAll" resultType="user"> select * from User </select> -
注意:configuration 的加載順序
properties -> settings -> typeAliases -> typeHandlers -> objectFactory -> objectWrapperFactory -> reflectorFactory -> plugins -> environments -> databaseIdProvider -> mappers
二、映射配置文件 mapper.xml
-
動態(tài)sql語句
- if 標簽
<select id="findByCondition" parameterType="user" resultType="user"> select * from User <where> <if test="id != null"> and id = #{id} </if> <if test="username != null"> and username = #{username} </if> </where> </select> - foreach 標簽
foreach標簽的屬性含義如下- collection:代表要遍歷的集合元素,注意編寫時不要寫#{},數組用array,集合使用 list 或者 collection 都可以
- open:代表語句的開始部分
- close:代表結束部分
- item:代表遍歷集合的每個元素,生成的變量名
- sperator:代表分隔符
<select id="findByIds" parameterType="list" resultType="user"> select * from User <where> <foreach collection="list" open="id in(" close=")" item="id" separator=","> #{id} </foreach> </where> </select> - SQL片段抽取
Sql 中可將重復的 sql 提取出來,使用時用 include 引用即可,最終達到 sql 重用的目的<!--抽取sql片段簡化編寫--> <sql id="selectUser" select * from User</sql> <select id="findById" parameterType="int" resultType="user"> <include refid="selectUser"></include> where id=#{id} </select> <select id="findByIds" parameterType="list" resultType="user"> <include refid="selectUser"></include> <where> <foreach collection="array" open="id in(" close=")" item="id" separator=","> #{id} </foreach> </where> </select>
- if 標簽
