1. 程式人生 > >三大框架之一 —— mybatis 的 mybatis-config.xml 檔案配置

三大框架之一 —— mybatis 的 mybatis-config.xml 檔案配置

1.常用標籤:

   標籤必須按照指定順序書寫:

properties(傳遞配置檔案), settings(設定命名方式), typeAliases(設定別名), 
        typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, 
environments(環境配置), 
        databaseIdProvider, 
mappers(SQL語句的配置)

2. 舉例:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 標籤必須按照指定順序書寫: properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers? -->
<properties resource="db.properties"> <!-- 宣告出來了四個變數,下面的配置檔案中可以直接使用 ${變數名} 獲取值 --> <property name="isUserCamelCase" value="true"/> </properties> <settings> <!-- 開啟資料庫下劃線命名方式和 java 駝峰命名方式之間的轉換 --> <setting name="mapUnderscoreToCamelCase"
value="${isUserCamelCase}" />
</settings> <typeAliases> <!-- 設定別名,使用別名代替原始的名字 --> <typeAlias type="com.zhiyou100.model.User" alias="_User" /> <typeAlias type="com.zhiyou100.model.Category" alias="_Category" /> <typeAlias type="com.zhiyou100.model.Topic" alias="_Topic" /> <typeAlias type="com.zhiyou100.model.Reply" alias="_Reply" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 自帶可用的資料庫連線池,不想使用設定 UNPOOLED --> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${user}" /> <property name="password" value="${password}" /> </dataSource> </environment> <environment id="product"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> </dataSource> </environment> </environments> <!-- 這裡的環境配置也可以直接寫,不過不推薦,不方便修改和維護 <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/zyonlineforum" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> --> <mappers> <!-- 使用 xml 的方式配置 --> <mapper resource="com/zhiyou100/mapper/CategoryMapper.xml" /> <!-- 使用註解的方式配置 ,直接在CategoryDao 介面方法上面寫查詢語句,例: @Select("select * from category") List<Category> listCategory(); --> <mapper class="com.zhiyou100.dao.CategoryDao" /> <mapper resource="com/zhiyou100/mapper/UserMapper.xml" /> </mappers> </configuration>

3 . ModelMapper.xml 檔案配置‘初級版’基本查詢語句:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


                    <!-- 對應model類介面的路徑 -->
<mapper namespace="com.zhiyou100.dao.UserDao">


    <!-- 字串拼接使用:${value} -->
    <!-- select * from user where username like #{value} -->

    <!-- id 就是對應的方法名 parameterType 傳遞的引數  resultType 返回值型別 ,有就寫,沒有不寫--> 
    <select id="listUserByName" parameterType="String" resultType="_User">
        select * from user where username like '%${value}%' <!-- 模糊查詢 -->
    </select>


    <!-- 
                    多引數:
            1. 封裝為物件
            2. 使用 HashMap
            3. 使用引數索引:
                    arg0,arg1,...
                    param1,param2,...
     -->
    <select id="listUserByNameOrEmail" resultType="_User">
        select * from user where username like #{param1} or email like #{param2}
    </select>

</mapper>

4 . ModelMapper.xml 檔案配置‘高配版’多引數查詢:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zhiyou100.dao.UserDao">

    <!-- where 標籤,用來拼接條件,會忽略緊跟著的一個 and -->
    <!-- 登入註冊功能中的查詢,自動判斷username 或 id 是否有輸入  -->
    <select id="listUserBy" parameterType="_User" resultType="_User">
        select * from user
        <where>
            <if test="username!=null and username!=''">
                and username like #{username}
            </if>
            <if test="id!=null">
                and id = #{id}
            </if>
        </where>
    </select>

<!-- 查詢條件有多個,是同一型別 username,可以使用foreach -->
    <select id="listUserSearch" resultType="_User">
        select * from user
        <where>
            <foreach collection="array" item="item">
                and username like #{item}
            </foreach>
        </where>
    </select>
    <!-- foreach 迴圈, collection:迴圈的集合,預設引數名字叫做 array item:集合中的每個元素 separator:for 
        迴圈拼接後的每隔字串之間使用這個分隔符分隔 open:for 左邊的語句,可以不使用 close:for 迴圈右邊的語句,可以不使用 -->

    <select id="listUserIn" resultType="_User">
        select * from user
        <where>
        <!-- 查詢多個 id= #{item} 值對應的user -->
            <foreach collection="array" item="item" separator="," open="id in ("
                close=")">
                #{item}
            </foreach>
        </where>
    </select>

    <!-- 獲取插入資料的主鍵: 方案1:使用 selectKey 方案2:在 insert 標籤增加 useGeneratedKeys="true" 
        keyProperty="id" 兩個屬性 無論哪種方案,獲得的主鍵都在 user 物件的 id 屬性中 -->

    <insert id="saveUser" parameterType="_User" useGeneratedKeys="true"
        keyProperty="id">

        <!-- <selectKey order="AFTER" resultType="long" keyProperty="id"> select 
            LAST_INSERT_ID() </selectKey> -->

        insert into user
        (username, password, email)
        values
        (#{username}, #{password}, #{email})

    </insert>
</mapper>

5 . ModelMapper.xml 檔案配置‘實用版’多表連線查詢(resultMap):

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhiyou100.dao.TopicDao">


    <resultMap type="_Topic" id="topicResultMap1">

        <!--使用 resultMap 自定義列名和屬性名 的 對映關係,表裡面gmt_create這一列與Topic 類裡面
                publishTime 屬性對應上了
         -->
        <result property="publishTime" column="gmt_create" />
    </resultMap>

    <select id="listTopicByCategoryId" resultMap="topicResultMap1">
        select * from topics where c_id = #{cId}
    </select>

    <resultMap type="_Topic" id="topicResultMap2">

        <!-- 查詢出來的是 topic物件下面的一個屬性 user, 標籤:association  -->
        <association property="user" javaType="_User">
            <id property="id" column="id" />
            <result property="password" column="password" />
            <result property="username" column="username" />
        </association>
    </resultMap>

    <select id="listTopicByCategoryIdwithUser" resultMap="topicResultMap2">
        select t.*,user.*
        from topics as t,user
        where t.c_id =#{cId} and t.u_id = user.id;
    </select>

    <resultMap type="_Topic" id="topicResultMap3">

        <id property="id" column="t_id" />
        <result property="title" column="t_title"/>
        <!-- 查詢出來的是 topic下面的一個屬性user 集合 , 標籤:collection -->
        <collection property="replies" ofType="_Reply">
            <id property="id" column="r_id" />
            <result property="content" column="r_content" />
        </collection>
    </resultMap>
            <!-- 不能寫 t.*  全部查詢,一個個查詢,按需要-->
        select t.id as t_id,t.title as t_title,r.id as r_id,r.content as r_content
        from topics as t,reply as r
        where t.id = #{id} and r.t_id = t.id;
    </select>

</mapper>