something about MyBatis

Posted 背时的哥哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了something about MyBatis相关的知识,希望对你有一定的参考价值。

1.入门

1.基于xml构建SqlSessionFactory

1.编写配置文件

<?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>
    <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://127.0.0.1:3306/lessontest"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="BookMapper.xml"/>
    </mappers>


</configuration>

2.编写映射文件

<?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.star.dao.BookDao">

<insert id="save" parameterType="com.star.entity.Book">
    insert into t_book values (default ,#{bookName},#{price})
</insert>

    <delete id="delete" parameterType="int">
        delete from t_book where id=#{id}
    </delete>

    <update id="update" parameterType="com.star.entity.Book">
        update t_book set bookname=#{bookName},price=#{price} where id=#{id}
    </update>

    <select id="query" resultType="com.star.entity.Book">
        select * from t_book
    </select>
</mapper>

3.创建SqlSessionFactory

编写工具类MyBatisUtil来完成创建

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
    
    static{
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

官方文档写到:SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
所以在此,使用静态代码块来创建SqlSessionFactory.

4.测试

public class Test {

    private SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();


    @org.junit.Test
    public void save(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BookDao mapper = sqlSession.getMapper(BookDao.class);
        Book book = new Book(100,"lll",19.0);
        int save = mapper.save(book);
        sqlSession.commit();
        sqlSession.close();
    }
    

    @org.junit.Test
    public void query(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BookDao mapper = sqlSession.getMapper(BookDao.class);
        List<Book> query = mapper.query();
        for (Book book : query) {
            System.out.println(book);
        }
    }

2.基于配置类构建SqlSessionFactory

将之前的工具类MyBatisUtil 中的静态代码块改成如下配置即可。

static {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/lessontest");
        dataSource.setUsername("root");
        dataSource.setPassword("123");
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development",transactionFactory,dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(BookMapper.class);//此处添加映射
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    }

此处MyBatis会根据映射(BookMapper.class)会自动查找并加载它(在这个例子中,基于类路径和 BookMapper.class 的类名,会加载 BookMapper.xml)。但这两个文件需要拥有相同的路径名:(否则找不到映射关系)
在这里插入图片描述
在这里插入图片描述

2.源码分析

1.解析配置文件

MyBatis通过XMLConfigBuilder类解析配置文件,并将配置转换为javaBean。就添加mapper为例:

1.添加mapper

将解析到的mapper标签的内容配置到Configuration中。在这里插入图片描述

在这里插入图片描述

2.注册mapper

在上一步中configuration调用addMappers()方法添加mapper实则是通过类MapperRegistry注册mapper。在这里插入图片描述
在此将mapper与mapper.xml建立映射关系

3.通过Executor执行器执行sql语句

例如查询方法:

 public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
        ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
        if (this.closed) {
            throw new ExecutorException("Executor was closed.");
        } else {
            if (this.queryStack == 0 && ms.isFlushCacheRequired()) {
                this.clearLocalCache();
            }

            List list;
            try {
                ++this.queryStack;
                list = resultHandler == null ? (List)this.localCache.getObject(key) : null;
                if (list != null) {
                    this.handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
                } else {
                    list = this.queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
                }
            } finally {
                --this.queryStack;
            }

            if (this.queryStack == 0) {
                Iterator var8 = this.deferredLoads.iterator();

                while(var8.hasNext()) {
                    BaseExecutor.DeferredLoad deferredLoad = (BaseExecutor.DeferredLoad)var8.next();
                    deferredLoad.load();
                }

                this.deferredLoads.clear();
                if (this.configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
                    this.clearLocalCache();
                }
            }

            return list;
        }
    }

以上是关于something about MyBatis的主要内容,如果未能解决你的问题,请参考以下文章

something about topojson

Something About Variable

something about SAM

Somethings About 《c++编程思想》

something about gdb

Something about the microsoft HttpContext domain design