1. 程式人生 > >mybatis框架——配置檔案詳解

mybatis框架——配置檔案詳解

一、全域性配置檔案

1、概覽

全域性配置檔案(SqlMapConfig.xml)的配置內容和順序如下(順序不能亂):

  • Properties(屬性)
  • Settings(全域性引數設定)
  • typeAliases(類型別名)
  • typeHandlers(型別處理器)
  • objectFactory(物件工廠)
  • plugins(外掛)
  • environments(環境資訊集合)
  • environment(單個環境資訊)
  • transactionManager(事物)
  • dataSource(資料來源)
  • mappers(對映器)

2、常用配置

1.Properties

        即配置載入properties檔案,首先建立db.properties:

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
db.username=root
db.password=root

那麼配置檔案:

<configuration>
    <!-- 載入java的配置檔案或者宣告屬性資訊 -->
    <properties resource="db.properties">
    </properties>
​
    <!-- 配置mybatis的環境資訊,與spring整合,該資訊由spring來管理 -->
    <environments default="development">
        <environment id="development">
            <!-- 配置JDBC事務控制,由mybatis進行管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置資料來源,採用mybatis連線池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
</configuration>

注意,如果:

<properties resource="db.properties">
    <property name="db.username" value="123" />
</properties>

還是會載入properties檔案中的username,因為先載入配置內容,再載入properties檔案,後者會覆蓋前者。

parameterType的值會和properties的屬性值發生衝突。

2.typeAliases

       對po類進行別名的定義,其中mybatis支援的別名有:

               別名                  原名
_byte byte
_long long 
_short short 
_int int 
_integer int 
_double double 
_float float 
_boolean boolean 
string  String 
byte Byte 
long Long 
short Short 
int Integer 
integer Integer 
double Double 
boolean Boolean 
float Float 
date Date 
decimal BigDecimal 
bigdecimal BigDecimal 

當然也可以自定義別名:

<!-- 自定義別名 -->
<typeAliases>
    <!-- 單個別名定義 -->
    <!-- <typeAlias type="com.itheima.mybatis.po.User" alias="user"/> -->
​
    <!-- 批量別名定義(推薦) -->
    <!-- package:指定包名稱來為該包下的po類宣告別名,預設的別名就是類名(首字母大小寫都可) -->
    <package name="com.itheima.mybatis.po" />
</typeAliases>

那麼在對映檔案中就可以使用user來替代其全限定名。

3.mappers

在引入對映檔案時有如下幾種格式:

  • <mapper resource=’’/>:使用相對於類路徑的資源【如:<mapper resource="sqlmap/User.xml" />】
  • <mapper url=’’/>:使用完全限定路徑【如:<mapper url="file:///D:\workspace_spingmvc\mybatis_01\config\sqlmap\User.xml" />】
  • <mapper class=’’/>:使用mapper介面的全限定名【如:<mapper class="cn.itcast.mybatis.mapper.UserMapper"/>】
  • <package name=’’/>(推薦):註冊指定包下的所有對映檔案【如:<package name="cn.itcast.mybatis.mapper"/>】

注意:後兩種方法要求mapper介面和mapper對映檔案要名稱相同,且放到同一個目錄下。

二、對映檔案

1、輸入對映

1.簡單型別

2.Pojo型別

參考入門中新增使用者的對映檔案

3.包裝pojo型別

      在綜合查詢時,可能會根據使用者資訊、商品資訊、訂單資訊等作為條件進行查詢,使用者資訊中的查詢條件由:使用者的名稱和性別進行查詢。需要先建立pojo的包裝類:

public class UserQueryVO {
    private User user;//使用者資訊
        //setget
}

然後在對映檔案中:

<!-- 綜合查詢,查詢使用者列表 -->
<select id="findUserList" parameterType="com.itheima.mybatis.po.UserQueryVO" resultType="user">
        SELECT * FROM user WHERE
        username LIKE '%${user.username}%'
        AND sex=#{user.sex}
</select>

在Mapper介面中:

public List<User> findUserList(UserQueryVO vo);

4.Map型別

       同傳遞POJO物件一樣,map的key相當於pojo的屬性。對映檔案如下:

<!-- 傳遞hashmap綜合查詢使用者資訊 -->
<select id="findUserByHashmap" parameterType="hashmap" resultType="user">
  select * from user where id=#{id} and username like '%${username}%'
</select>

2、輸出對映

1.resultType

      使用resultType進行結果對映時,需要查詢出的列名和對映的物件的屬性名一致,才能對映成功。如果查詢的列名和物件的屬性名全部不一致,那麼對映的物件為空;如果查詢的列名和物件的屬性名有一個一致,那麼對映的物件不為空,但是隻有對映正確那一個屬性才有值。

說明:如果查詢的sql的列名有別名,那麼這個別名就是和屬性對映的列名。

1.簡單型別

       注意,對簡單型別的結果對映也是有要求的,查詢的列必須是一列,才能對映為簡單型別。綜合查詢時,需要根據綜合查詢的新增查詢使用者的總數,首先對映檔案:

<select id="findUserCount" parameterType="com.itheima.mybatis.po.UserQueryVO"  resultType="int">
    SELECT count(*) FROM user WHERE
               username LIKE '%${user.username}%'
               AND sex=#{user.sex}
</select>

在Mapper介面中:

//綜合查詢使用者總數
public int findUserCount(UserQueryVO vo);

2.Pojo物件和pojo列表

參考入門程式之根據使用者ID查詢使用者資訊和根據使用者名稱稱模糊查詢使用者列表

2.resultMap

      使用resultMap進行結果對映時,不需要查詢的列名和對映的屬性名必須一致。但是需要宣告一個resultMap,來對列名和屬性名進行對映。如,對以下sql查詢的結果集進行物件對映:

Select id id_,username username_,sex sex_ from user where id = 1;

在對映檔案中:

<resultMap type="user" id="UserRstMap">
    <id column="id_" property="id" />
    <result column="username_" property="username" />
    <result column="sex_" property="sex" />
</resultMap>
​
<select id="findUserRstMap" parameterType="int" resultMap="UserRstMap">
    Select id id_,username username_,sex sex_ from user where id = #{id}
</select>

說明:

id標籤:專門為查詢結果中唯一列對映

result標籤:對映查詢結果中的普通列

在Mapper介面中:

public User findUserRstMap(int id);

3、動態sql

       在mybatis中,它提供了一些動態sql標籤,可以讓程式設計師更快的進行mybatis的開發,這些動態sql可以通過sql的可重用性。常用的動態sql標籤:if標籤、where標籤、sql片段、foreach標籤。

1.If標籤/where標籤

      在綜合查詢時,查詢條件由使用者來輸入,使用者名稱稱可以為空,需要滿足這種情況下的sql編寫:

<!-- 綜合查詢,查詢使用者列表 -->
<select id="findUserList" parameterType="com.itheima.mybatis.po.UserQueryVO"  resultType="user">
    SELECT * FROM user
    <where>
        <if test="user != null">
            <if test="user.username != null and user.username != ''">
                AND username LIKE '%${user.username}%'
            </if>
            <if test="user.sex != null and user.sex != ''">
                AND sex = #{user.sex}
            </if>
        </if>   
    </where>
</select>

解釋:

  • where標籤:預設去掉後面第一個AND,如果沒有引數,則把自己幹掉(還有一個set標籤,去掉最後面的','號)
  • if標籤:可以對輸入的引數進行判斷
  • test:指定判斷表示式

除了可以將程式碼直接寫在該處,還可以寫在sql塊中,然後呼叫:

<sql id="whereClause">
    <if test="user != null">
        <if test="user.username != null and user.username != ''">
            AND username LIKE '%${user.username}%'
        </if>
        <if test="user.sex != null and user.sex != ''">
            AND sex = #{user.sex}
        </if>
    </if>
</sql>
​
<select id="findUserList" parameterType="com.itheima.mybatis.po.UserQueryVO"
    resultType="user">
    SELECT * FROM user
    <where>
        <!-- 引入sql片段 -->
        <include refid="whereClause" />
    </where>
</select>

注意:sql片段內,最好不用將where和select關鍵字宣告在內。

2.Foreach標籤

       可以迴圈傳入引數值。綜合查詢時,會根據使用者ID集合進行查詢(批量刪除),如下面SQL:

SELECT * FROM USER WHERE id IN (1,2,10)

首先修改包裝pojo:

public class UserQueryVO {
    private User user;//使用者資訊
    private List<Integer> idList;//ID集合
}

然後在sql片段中需要拼湊出:AND id IN (#{id},#{id},#{id}) 

<sql id="whereClause">
    <if test="idList != null">
        AND id IN
        <foreach collection="idList" item="id" open="(" close=")"
            separator=",">
            #{id}
        </foreach>
    </if>
</sql>

解釋:

  • collection:表示pojo中集合屬性的屬性名稱
  • item:為遍歷出的結果宣告一個變數名稱
  • open:遍歷開始時,需要拼接的字串
  • close:遍歷結束時,需要拼接的字串
  • separator:遍歷中間需要拼接的連線符

如果直接傳遞的是List集合,則:

<select id="findUsersByIdList" parameterType="java.util.List" resultType="user">
    SELECT * FROM USER
    <where>
        <if test="list  != null and list.size > 0">
            <foreach collection="list" item="id" open="AND id IN (" close=")" separator=",">
                #{id}
            </foreach>
        </if>
    </where>
</select>