Mybatis 3 學習筆記整理

在寫這篇文章時,該怎麼去寫,思考了良久。因爲已經看過有兩位大神已經深入分析了Mybatis,一位是源碼道,還有一位是zhjh256。這裏寫的目的有兩個,一是增強自己的總結能力,加深對Mybatis的理解,二是記錄下來,因爲好記性不如爛筆頭。總的來說,看別人寫的文章,沒有經過自己的思考總結,知識還是別人的。
兩位大神,一位是從基礎入手,以由淺入深的方式分析了JDBC怎麼演變到Mybatis的漸變過程。這種方式非常值得我們學習。由此可知,框架的特性,爲了解決某些問題,高度封裝等。

        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&characterEncoding=utf-8";
        String username = "root";
        String password = "root";
        // 創建使用緩存池的數據源
        // 創建事務
        // 創建環境
        // 創建配置對象
        // 創建回話工廠
        DataSource dataSource = new PooledDataSource(driver, url, username, password);

        TransactionFactory transactionFactory = new JdbcTransactionFactory();

        Environment environment = new Environment("development", transactionFactory, dataSource);

        Configuration configuration = new Configuration(environment);

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);


Mybatis 的xml分爲兩類:一類是基礎配置文件,一類是映射文件

SqlSessionFactoryBuilder

SqlSessionFactory

SqlSession

映射器:接口 + 註解接口 + XML(推薦)

引入映射器方式:

  1. 文件路徑
    <mapper resource="com/xxx/dao/xxxMapper.xml" />
    note】相對於類的路徑。
  2. 包名
    <package name= "com.xxx.dao"/>
    note】此種方法要求mapper接口名稱和mapper映射文件名稱相同,且放在同一個目錄中(編譯後)。

  3. <mapper class= "com.xxx.dao.xxxMapper"/>
    note】此種方法要求mapper接口名稱和mapper映射文件名稱相同,且放在同一個目錄中(編譯後)。
  4. URL
    <mapper url= "file:///xxxxxxxxxx/xxxMapper" />
    ps】若不知道這個URL怎麼寫,則把文件丟進瀏覽器可在地址欄看到。這種方式不常用。
<resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
</resources>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章