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>

猜你喜欢

转载自blog.csdn.net/qq_35070673/article/details/78542637