Mybatis連線池丶動態sql丶抽取sql語句
阿新 • • 發佈:2018-12-16
當實體類的屬性(uid)與資料庫的欄位(id)不一致的時候
對於增刪改: 只需在傳入引數後的佔位符中把對應的屬性傳遞進去就行 對於查詢: 1. 可以通過資料庫的別名來解決 select id as uid from user 2. 可以使用resultMap來設定 <resultMap id="userMap" type="com.qin.domain.User(或者別名)"> <id property = "uid" column="id"/> <result property = "username" column="username"/> </resultMap> id 標籤:用於指定主鍵欄位 result 標籤:用於指定非主鍵欄位 column 屬性:用於指定資料庫列名 property 屬性:用於指定實體類屬性名稱 * 當實體類的屬性與表的欄位不一致的時候才使用resultMap,一樣的時候使用resultType
Mybatis中的連線池
1. Mybatis中的連線池提供了3種方式的配置 配置的位置: 主配置檔案SqlMapConfug.xml中的dataSource標籤,type屬性就是表示採用何種 連線池方式 type屬性的取值: POOLED: 採用傳統的javax.sql.DataSource規範中的連線池,mybatis中有針對規範的實現 UNPOOLED: 採用傳統的獲取連線的方式,雖然也是使用javax.sql.DataSource規範中的連線池,但是並沒有 每次都是建立一個新的連線. JDNI: java naming and directory interface 使用的是伺服器中提供的JNDI技術實現,來獲取DataSource物件,不同的伺服器所能拿到的物件不同 注意:不是web或者maven工廠是不可以使用的
事務性
設定自動提交: session = factory.openSession(true);
動態sql語句
if <select id="findByUser" resultType="user" parameterType="user"> select * from user where 1=1 <if test="username!=null and username != '' "> and username like #{username} </if> <if test="address != null"> and address like #{address} </if> </select> 注意:<if>標籤的 test 屬性中寫的是物件的屬性名,如果是包裝類的物件要使用 OGNL 表示式的寫法。 where 替換 where 1 = 1 並去掉第一個and foreach <select id="findInIds" resultType="user" parameterType="queryvo"> select * from user <where> <if test="ids != null and ids.size() > 0"> <foreach collection="ids" open="id in ( " close=")" item="uid" separator=","> #{uid} </foreach> </if> </where> </select> <foreach>標籤用於遍歷集合,它的屬性: collection:代表要遍歷的集合元素,注意編寫時不要寫#{} open:代表語句的開始部分 close:代表結束部分 item:代表遍歷集合的每一個元素,生成的變數名 separator:代表分隔符 trim(多用於insert) 與set(多用於update中的多個條件的,)
Mybatis簡化sql片段(抽取sql語句)
* 抽取重複的語句程式碼片段
<sql id="defaultSql">
select * from user
</sql>
* 引用程式碼片段
<include refid="defaultSql"></include>