MyBatis概述

MyBatis概述

mytatis的介紹

和jdbc比較:
mybatis抽離出數據庫的連接,關閉的操作.抽離了sql語句,並且可以自動的進行參數的設置,封裝結果集.

hibernate比較:
- 性能:mybatis較hibernate高
- sql靈活性:mybatis較hibernate高
- 配置文件:mybatis較hibernate多(維護困難)
- 數據庫的無關性:mybatis較hibernate低

mybatis是一個封裝jdbc基於sql配置的半自動化ORM框架,使用於互聯網,電商項目.前身ibatis,後改名爲mybatis,apache的開源項目,已經遷移到GitHub代碼的託管網站.

mabatis的配置文件

全局配置文件:sqlmapconfig.xml

文件中的配置項是由順序的,按照官方圖來配.
configuration
- properties
- settings
- typeAliases
- typeHandlers
- objectFactory
- plugins
- environments
* envioronment
* transactionManager
* dataSource
- databaseIdProvider
- mappers

例如:

    <!-- resource:表示從classpath下加載 -->
    <properties resource="db.properties">
        <property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
    </properties>

2. settings: 全局參數設置
設置延遲加載:

    <settings>
        <!-- 開啓延遲加載,默認值爲true-->
        <setting name="lazyLoadingEnabled" value="true" />
        <!--設置積極的懶加載,默認值是true-->
        <setting name="aggressiveLazyLoading" value="false" />
    <settings>
  1. typeAliases:類型別名

    <!-- 自定義別名 -->
    <typeAliases>
        <!-- type:指定java對象類型 -->
        <!-- alias:給java對象取得別名,對大小寫不敏感 -->
        <typeAlias type="com.aric.mybatis.po.User" alias="user"/>
        <!-- 掃描包的方式,別名就是包下類的類名,不區分大小寫 -->
        <package name="com.aric.mybatis.po"/>
    </typeAliases>
    
  2. mappers:

    <mappers>
        <!-- resource:從classpath下加載sql映射文件 -->
        <!-- <mapper resource="sqlmap/User.xml"/>
        <mapper resource="mapper/User.xml"/> -->
        <!-- 指定mapper接口的類路徑 -->
        <!-- 要求:1.mapper接口 和sql的映射文件在同一個目錄下,2.mapper接口的類名和映射文件的名稱要一致-->
        <!-- <mapper class="com.aric.mybatis.mapper.UserMappser" /> -->
        <!--包掃描-->
        <package name="com.aric.mybatis.mapper" />
    </mappers>
    

映射文件

<!-- namespace:命令空間,類似包 -->
<mapper namespace="test">

    <!-- id:代表sql語句的唯一標識 -->
    <!-- resultType:查詢結果集的類型 -->
    <!-- parameterType:輸入參數的數據類型 -->
    <!-- #{id}:用於接收數據,代表一個佔位符,表示將外部傳遞過來的數據映射到sql語句中 -->
    <!-- #{}中的變量可以是任意的(前提條件是:輸入參數的數據類型是簡單的類型) -->
    <select id="getUserById" parameterType="int" resultType="com.aric.mybatis.po.User" >
        select * from user where id=#{idd}
    </select>

    <!-- 如果查詢的結果是列表,那麼resultType只需指定列表中元素的類型 -->
    <select id="getUserByUsername" parameterType="String" resultType="com.aric.mybatis.po.User">
        <!-- ${value}表示sql串的拼接,${value}中變量必須是value(如果輸入的是簡單類型) -->
        select * from user where username like "%${value}%"
    </select>

    <!-- 添加用戶 -->
    <!-- parameterType指定java對象,獲取值時#{}中必須是java對象中的屬性名 -->
    <insert id="addUser" parameterType="user">
        <!-- keyProperty:查詢到的主鍵,放入到User對象中的id屬性 -->
        <!-- resultType:表示查詢到的主鍵的類型 -->
        <!-- order:表示在插入語句之後還是之前執行 -->
        <!-- <selectKey keyProperty="id" resultType="int" order="AFTER">
            select LAST_INSERT_ID()
        </selectKey> -->
        <!-- insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}); -->
        <selectKey keyProperty="id" resultType="String" order="BEFORE">
            select uuid()
        </selectKey>
        insert into user(id,username,birthday,sex,address) values(#{id},#{username},#{birthday},#{sex},#{address});
    </insert>

    <!-- 添加用戶 -->
    <!-- parameterType指定java對象,獲取值時#{}中必須是java對象中的屬性名 -->
    <insert id="addUserUUID" parameterType="userUUID">
        <!-- keyProperty:查詢到的主鍵,放入到User對象中的id屬性 -->
        <!-- resultType:表示查詢到的主鍵的類型 -->
        <!-- order:表示在插入語句之後還是之前執行 -->
        <selectKey keyProperty="id" resultType="String" order="BEFORE">
            select uuid()
        </selectKey>
        insert into userUUID(id,username,birthday,sex,address) values(#{id},#{username},#{birthday},#{sex},#{address});
    </insert>

    <!-- 刪除用戶 -->
    <delete id="deleteUserById" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <!-- 更新用戶 -->
    <update id="updateUserById" parameterType="user">
        update user set birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>

</mapper>

注意點

#{xxx}表示一個佔位符,jdbc中的?通過#{xxx} 可以將外部傳遞過來映射到sql語句中,可以有效的防止sql注入.
xxxsql,sql.{xxx},輸入的參數類型是簡單類型,那麼${xxx}中的xxx必須是value.

parameterType:表示輸入參數的數據類型
resultType:輸出結果的數據類型,如果查詢的是列表,那麼resultType只需要設置列表中的元素的數據類即可.

核心API

執行流程:
加載sqlmapconfig.xml,通過sqlsessionfactorybuilder,構建sqlsesionfactroy對象.由它構建sqlsession提供增刪改查等操作數據庫的方法.

SqlSessionFactoryBuilder

SqlSessionFactory build(InputStream inputStream)
SqlSessionFactory build(InputStream inputStream,String environment)
SqlSessionFactory build(InputStream inputStream,Properties properties)
SqlSessionFactory build(InputStream inputStream,String env,Properties props)
SqlSessionFactory build(Configuration config)

案例

String resource = "org/mybatis/builder/mybatis-config.xml";
InputStream  inputStream = Resource.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.builder(inputStream);

SqlSessionFactory

創建SqlSession的方法:

SqlSession openSession()
SqlSession openSession(boolean autoCommit)
SqlSession openSession(Connection connection)
SqlSession openSession(TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType)
SqlSession openSession(ExecutorType execType, boolean autoCommit)
SqlSession openSession(ExecutorType execType, Connection connection)
Configuration getConfiguration();

• Transaction: Do you want to use a transaction scope for the session, or use auto-commit
(usually means no transaction with most databases and/or JDBC drivers)?
• Connection: Do you want MyBatis to acquire a Connection from the configured DataSource for
you, or do you want to provide your own?
• Execution: Do you want MyBatis to reuse PreparedStatements and/or batch updates (including
inserts and deletes)?

用openSession方法獲取的SqlSession有以下特點:
- 開啓事務,但是不會自動提交事務
- 將從配置文件中配置的數據源中獲取連接(Connection)
- 事務級別默認使用驅動或數據源的
- 預編譯不會被重用,不會批量更新

列舉3個執行類型參數(ExecutorType):
- ExecutorType.SIMPLE 每次執行都預編譯
- ExecutorType.REUSE 重用預編譯
- ExecutorType.BATCH 批量預編譯

SqlSession

SqlSession執行增刪改查以及事務操作.

    <T> T selectOne(String statement, Object parameter)
    <E> List<E> selectList(String statement, Object parameter)
    <K,V> Map<K,V> selectMap(String statement, Object parameter, String mapKey)
    int insert(String statement, Object parameter)
    int update(String statement, Object parameter)
    int delete(String statement, Object parameter)

分頁查詢

    <E> List<E> selectList (String statement, Object parameter, RowBounds rowBounds)
    int offset = 100;
    int limit = 25;
    RowBounds rowBounds = new RowBounds(offset, limit);

    void select (String statement, Object parameter, ResultHandler handler)

ResultHandler參數:可以把每行記錄包裝成其他數據類型,如:List,Map,Set.只需要寫個接口.

    package org.apache.ibatis.session;
    public interface ResultHandler {
        void handleResult(ResultContext context);
    }

控制事務

    void commit()
    void commit(boolean force)
    void rollback()
    void rollback(boolean force)

緩存

一級緩存指的就是sqlsession,在sqlsession中有一個數據區域,是map結構,這個區域就是一級緩存區域。一級緩存中的key是由sql語句、條件、statement等信息組成一個唯一值。一級緩存中的value,就是查詢出的結果對象。

二級緩存指的就是同一個namespace下的mapper,二級緩存中,也有一個map結構,這個區域就是一級緩存區域。一級緩存中的key是由sql語句、條件、statement等信息組成一個唯一值。一級緩存中的value,就是查詢出的結果對象。

一級緩存是默認使用的。
二級緩存需要手動開啓。

二級緩存的配置
1. 開啓二級緩存中開關

    <!--二級緩存總開關-->
    <setting name="cacheEnabled" value="true">

2. 在mapper映射文件中開啓二級緩存

    <!--開啓二級緩存,默認使用了PerpetualCache-->
    <cache/>

3. 禁止使用緩存
useCache=”false”
4. 刷新緩存
select語句默認是false,增刪改語句默認是true

    flushCache="true"

Mappers

Mapper是個接口,裏面定義方法匹配SqlSession中方法.

    public interface AuthorMapper {
     // (Author) selectOne("selectAuthor",5);
     Author selectAuthor(int id); 
     // (List<Author>) selectList(“selectAuthors”)
     List<Author> selectAuthors();
     // (Map<Integer,Author>) selectMap("selectAuthors", "id")
     @MapKey("id")
     Map<Integer, Author> selectAuthors();
     // insert("insertAuthor", author)
     int insertAuthor(Author author);
     // updateAuthor("updateAuthor", author)
     int updateAuthor(Author author);
     // delete("deleteAuthor",5)
     int deleteAuthor(int id);
    }

Mapper註解,參考Mybatis官方文檔.
示例:

    @Insert("insert into table3 (id, name) values(#{nameId}, #{name})")
    @SelectKey(Statement="call next value for TestSequence",keyProperty ="nameId",before=true, resultType=int.class)
    int insertTable3(Name name);

    @Insert("insert into table2 (name) values(#{name})")
    @SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
    int insertTable2(Name name);

動態sql

MyBatis使用OGNL表達式,來支持一些常用的標籤.
- if
- choose(when,otherwise)
- trim(where,set)
- foreach

案例:

if

<!-- 根據用戶id和用戶名稱查詢,需要進行判斷,如果id爲空,就以名稱查詢,如果名稱爲空,就以id查詢,如果都爲空,查詢所有 -->
<select id="getUserByIdOrUsername" parameterType="user" resultType="user">
    select * from user 
    <!-- where:可以去掉多餘的and,拼接where條件 -->
    <where>
        <if test="id != null">
            and id=#{id}
        </if>
        <if test="username != null and username !=''">
            and username like '%${username}%'
        </if>
    </where>
</select>

choose, when, otherwise

    <select id="findActiveBlogLike" resultType="Blog">
        SELECT * FROM BLOG WHERE state = ‘ACTIVE’
        <choose>
            <when test="title != null">
                AND title like #{title}
            </when>
            <when test="author != null and author.name != null">
                AND author_name like #{author.name}
            </when>
            <otherwise>
                AND featured = 1
            </otherwise>
        </choose>
    </select>

trim, where, set

<!-- 更新用戶 -->
<update id="updateUser" parameterType="user">
    update user
    <!-- set:更新並且可以去掉多餘的"," -->
    <set>
        <if test="address != null and address != ''">
            address =#{address},
        </if>
        <if test="sex != null and sex != ''">
            sex =#{sex},
        </if>
        <if test="username != null and username != '' ">
            username =#{username}
        </if>
    </set>
    where id=#{id}
</update>

<!--去掉多餘的前綴-->
<trim prefix="WHERE" prefixOverrides="AND |OR ">
    ...
</trim>

<!--去掉多餘的後綴-->
<trim prefix="SET" suffixOverrides=",">
    ...
</trim>

foreach

<!-- 查詢id在一個範圍的用戶 -->
<select id="getUserListByForEach" parameterType="QueryVo" resultType="user">
    select * from user 
    <where>
        <!-- collection:queryvo中的集合屬性ids -->
        <!-- open:表示開始的sql串 -->
        <!-- close:表示結束的sql串 -->
        <!-- item:要遍歷的變量 -->
        <!-- separator:循環遍歷時,指定分割的字符 -->
        <foreach collection="ids" open="id in(" close=")" item="id" separator=",">
            `#{id}`
        </foreach>
    </where>
</select>

bind

創建一個ognl表達式,用於語句中.

  <select id="selectBlogsLike" resultType="Blog">
     <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
     SELECT * FROM BLOG WHERE title LIKE #{pattern}
  </select>

Multi-db vendor support

    <insert id="insert">
        <selectKey keyProperty="id" resultType="int" order="BEFORE">
            <if test="_databaseId == 'oracle'">
                select seq_users.nextval from dual
            </if>
            <if test="_databaseId == 'db2'">
                 select nextval for seq_users from sysibm.sysdummy1"
            </if>
        </selectKey>
        insert into users values (#{id}, #{name})
    </insert>

Pluggable Scripting Languages For Dynamic SQL

爲動態sql定製可插拔腳本語句

使用步驟:
實現LanguageDriver接口

    public interface LanguageDriver {

         ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql);

         SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType);

         SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType);

    }

再mybatis-config.xml或sqlmapconfig.xml文件中覆蓋默認別名,使用自定義

    <typeAliases>
         <typeAlias type="org.sample.MyLanguageDriver" alias="myLanguage"/>
    </typeAliases>
    <settings>
         <setting name="defaultScriptingLanguage" value="myLanguage"/>
    </settings>

在映射文件中使用

    <select id="selectBlog" lang="myLanguage">
        SELECT * FROM BLOG
    </select>

也可以在mapper中使用

    public interface Mapper {
         @Lang(MyLanguageDriver.class)
         @Select("SELECT * FROM BLOG")
         List<Blog> selectBlog();
    }

sql片段

抽取sql重複代碼,提供效率。

<sql id="userColumns"> id,username,password </sql>
<select id="selectUsers" resultType="map">
 select <include refid="userColumns"/>
 from some_table
 where id = #{id}
</select>

Dao開發

實現方式:
1. 傳統的Dao建一個dao 建立一個接口,再建實現類.
2. mapper代理的方式,只需要寫接口,不需要寫實現類,實現類由mybatis框架自動創建(官方推薦)

傳統的Dao

  • sqlsessionfactorybuilder當作一個工具類,一旦使用完畢,就應該銷燬,最佳使用範圍在方法內部.
  • sqlsessionfactory要單例存在,一旦創建就應當在整個程序運行期使用,沒必要創建一次.使用範圍整個運行期.(整合spring時,可以由spring來管理)
  • sqlsession是多例的,它線程不安全的,也不能被共享的,使用範圍是在方法的內部.而且,一旦使用完成,必須要關閉,在finally中關閉.

接口:

//根據用戶id查詢用戶
public User getUserById(Integer id);

//根據用戶名稱模糊查詢用戶列表
public List<User> getUserListByUsername(String username)

//添加用戶
public void addUser(User user);

實現類:

    private SqlSessionFactory factory;//需要注入

    public UserDaoImpl(SqlSessionFactory factory){
        this.factory = factory;
    }

    public User getUserById(Integer id)throws Exception{
        SqlSession sqlSession = factory.openSession();
        List<User> list = sqlSession.selectList("test.getUserByUsername",username);
        sqlSession.close();//應當在finally中關閉
        return list;
    }

    public void insertUser(User user){
        SqlSession sqlSession = factory.openSession();
        sqlSession.insert("","");
        sqlSession.commit();
        sqlSession.close();
    }

優化:
可以建立一個BaseDaoImpl 繼承sqlsesiondaosupport ,在此進行sqlsessionfactory注入。

mapper代理的方式

mapper代理的方式,只需要寫接口,不需要寫實現類,實現類由mybatis框架自動創建.
需要遵守規則:
1. sql的映射文件中的namespace要和Mapper接口中的類路徑(全限定名)一致
2. sql的映射文件中的sql的id要和mapper接口中的方法的名稱一致
3. sql的映射文件中的parameterType要和mapper接口中的方法的參數類型一致
4. sql的映射文件中的resultType要和mapper接口中的方法的返回值數據類型一致

        /**
         * 根據用戶名模糊查詢用戶
         * @param username
         * @return
         * @throws Exception
         */
        List<User> getUserByUsername(String username) throws Exception;
測試:

        //注入sqlsessionfactory
        //獲取sqlsession
        //通過sqlsession對象獲取mapper的代理對象(接口的實現類實例)
        UserMapper mapper = sqlSession.getMapper(UserMapper.class)
        mapper.getUserByUsername("張");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

多表查詢

輸出結果類型

  1. resultType,字段和java對象中屬性一致推薦使用resultType
  2. resultMap,字段和java對象中屬性不一致的情況比較多的時候使用resultMap

ResultMap

resultType使用時,設置值時需要查詢的列名和Java對象屬性名一致.如果不一致的時候,可以使用resultMap.使用時需要先定義,再使用.
resultMap做複雜的映射配置(多表查詢).

映射一對一關係

<!-- 定義多表查詢的resultMap -->
<resultMap type="com.aric.mybatis.po.Orders" id="getOrdersListUserResultMap">
    <!-- 主鍵映射配置 -->
    <!-- column:表示將查詢的列要映射到哪一個屬性中 -->
    <!-- property:表示要映射的屬性 -->
    <id column="id" property="id" />
    <id column="id" property="id"/>
    <!-- 普通列的配置 -->
    <!-- 如果是單表,相同的列和屬性可以不用配置 -->
    <result column="user_id" property="userId"/>
    <result column="number" property="number"/>
    <result column="createtime" property="createtime"/>
    <result column="note" property="note"/>
    <!-- association:表示一對一的映射關係 -->
    <!-- property:orders中的屬性 -->
    <!-- javaType:property對應的java類 -->
    <association property="user" javaType="com.aric.mybatis.po.User">
        <id column="username" property="username"/>
        <result column="address" property="address"/>
    </association>

</resultMap>

<!-- 多表查詢 -->
<select id="getOrdersListUserResultMap" resultMap="getOrdersListUserResultMap" >
    SELECT
        o.id,
        o.user_id AS userId,
        o.number,
        o.note,
        o.createtime,
        u.username,
        u.address
    FROM
        orders o
    LEFT JOIN USER u ON u.id = o.user_id
</select>

<!-- resultType -->
<select id="getOrdersUserList" resultType="com.aric.mybatis.po.OrdersCutom">
    SELECT
        o.id,
        o.user_id AS userId,
        o.number,
        o.note,
        o.createtime,
        u.username,
        u.address
    FROM
        orders o
    LEFT JOIN USER u ON u.id = o.user_id
</select>

映射一對多關係

<!-- 定義resultMap -->
<resultMap type="com.aric.mybatis.po.User" id="getUserListOrdersResultMap">
    <id column="id" property="id"/>
    <result column="username" property="username"/>
    <result column="birthday" property="birthday"/>
    <result column="sex" property="sex"/>
    <result column="address" property="address"/>
    <!-- 映射多對一關係 -->
    <!-- property:表示主表中的list屬性orders -->
    <!-- ofType:表示list中元素的數據類型 -->
    <collection property="orders" ofType="com.aric.mybatis.po.Orders">
        <!-- column是查詢的列 -->
        <id column="oid" property="id"/>
        <result column="number" property="number"/>
    </collection>
</resultMap>

<!-- 多表查詢,查詢用戶以及關聯的訂單 -->
<select id="getUserListOrdersResultMap" resultMap="getUserListOrdersResultMap">
    SELECT
        u.*,
        o.number,
        o.id AS oid
    FROM
        USER u
    LEFT JOIN orders o ON u.id = o.user_id
</select>

多對多映射

<!-- resultMap:定義查詢用戶關聯查詢訂單關聯查詢訂單明細及商品信息 -->
<resultMap type="user" id="resultMap_user_orders_details_items">
    <id column="user_id" property="id" />
    <result column="username" property="username"/>
    <!-- 一個用戶對應多個訂單 -->
    <collection property="orders" ofType="com.aric.mybatis.po.Orders">
        <id column="order_id" property="id" />
        <result column="number" property="number" />
        <!-- 一個訂單對應多個訂單明細 -->
        <collection property="orderdetail" ofType="com.aric.mybatis.po.OrderDetail">
            <id column="detail_id" property="id" />
            <!-- 一個訂單明細對應一個商品 -->
            <association property="items" javaType="com.aric.mybatis.po.Items">
                <id column="item_id" property="id" />
                <result column="name" property="name" />
            </association>
        </collection>
    </collection>
</resultMap>

<!-- 查詢用戶關聯查詢訂單關聯查詢訂單明細及商品信息  -->
<select id="selectUserOrders_details_items" resultMap="resultMap_user_orders_details_items">
    SELECT
        u.id AS user_id,
        u.username,
        ord.id AS order_id,
        ord.number,
        de.id AS detail_id,
        i.id AS item_id,
        i. NAME
    FROM
        USER u
    LEFT JOIN orders ord ON u.id = ord.user_id
    LEFT JOIN orderdetail de ON de.orders_id = ord.id
    LEFT JOIN items i ON de.items_id = i.id
</select>

mybatis和spring的整合

整合的步驟
1. 創建工程
2. 加入jar spring的包 mybatis的包 依賴包 數據庫驅動 數據連接池 整合包 日誌包
3. mybatis配置文件

    <?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>
        <!--全部交給spring管理,但是文件必須存在-->

    </configuration>

4. spring的配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util 
        http://www.springframework.org/schema/util/spring-util-4.0.xsd">

        <!-- 配置db.properties數據源 -->
        <context:property-placeholder location="classpath:db.properties" />

        <!-- 配置數據庫連接池 -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <!-- 配置連接池屬性 -->
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <property name="maxActive" value="10" />
            <property name="maxIdle" value="5" />
        </bean>

        <!-- 配置sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入mybatis配置文件 -->
            <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
            <!-- 注入連接池 -->
            <property name="dataSource" ref="dataSource"></property>
        </bean>

        <!-- 傳統dao開發方式 -->
    <!--    <bean id="userDao" class="com.aric.mybatis.dao.UserDaoImpl">
            <property name="sqlSessionFactory" ref="sqlSessionFactory" />
        </bean> -->

        <!--傳統dao開發方式:掃描包-->
        <context:component-scan base-package="com.aric.mybatis.dao" />

        <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
            mapperInterface:指定mapper的接口 用於生成此接口的代理對象 
            <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
            <property name="mapperInterface" value="com.aric.mybatis.mapper.UserMapper"></property>
        </bean> -->

        <!-- mapper掃描方式生成代理對象 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
            <!-- 指定掃描的包 :1.自動批量生成代理對象(接口的類名首字母小寫) 2.加載mapper映射文件 -->
            <property name="basePackage" value="com.aric.mybatis.mapper"></property>
        </bean>

    </beans>

5. 數據庫、日誌的配置文件
db.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
    jdbc.username=root
    jdbc.password=123

log4j.properties

    # Global logging configuration
    log4j.rootLogger=DEBUG, stdout
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.console.encoding=UTF-8
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章