一.基本介绍
已经好久没写博客了,其实心里一直想着写的,但就是静不下来。忽然醒悟不能在堕落下去,自己扶自己起来,逼着自己学习。老实说,之所以看源码,最开始纯粹是因为工作太闲,不敢相信吧。当自己不经意间成为工具人的时候,是时候想办法提高,改变自己了。 看源码过程是痛苦的,枯燥的,不断的调试。但是在这个过程中,对于思维推理能力的锻炼还是有成效的,希望大家能坚持!
二.Mybatis基本介绍
对于Mybatis的用途,特性以及和其他框架比较,网上介绍一大堆,天花乱坠,就不在赘述。我这里以源码的角度来看,Mybatis源码,相对于Spring,SpringMvc,Tomcat来说 ,个人认为是最简单的。所以接下来会先写一系列Mybatis的博客,之后再写Spring,Tomcat等相关源码博客。
在读源码之前,给出几点建议:
1.对Mybatis使用基本熟悉
2.阅读官方文档,主要是了解一些配置以及实现的功能
推荐网址:https://mybatis.org/mybatis-3/zh/getting-started.html(中文文档)
3.了解JDBC基本API
三.Mybatis基本使用
环境:jdk1.8,mybatis-3.5.3
基本使用,直接参照官网
1.导包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
2.创建配置文件 - mybatis-config.xml
<?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="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
BlogMapper.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="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} </select> </mapper>
3.写代码
String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//方式一
try (SqlSession session = sqlSessionFactory.openSession()) { //获取 SqlSession //查询 Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101); }
//方式二
try (SqlSession session = sqlSessionFactory.openSession()) { BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101); }
可以看见,上述代码在平时开发中好像完全没出现过。那是因为,现在项目,基本都是ssm,不得不说,Spring很强大。也正是太强大,将所有东西都隐藏起来,容易让开发人员忽略细节。
在实际项目中,正常代码(除配置文件外),Service层引入Dao层的接口,与数据库交互,直接调用Dao层接口方法即可。这是由于spring整合了mybatis,(mybatis-spring这个jar)。整合源码之后会说,本系列只单纯说Mybatis。
其实根据上述代码可以看到,可以简单的分为2步:
1.创建 SqlSessionFactory对象,这里面主要是配置文件 mybatis-config.xml解析,以及Mapper文件(BlogMapper.xml)解析
2.根据SqlSessionFactory获取 SqlSession对象,用于执行sql
好的,Mybatis基本介绍结束,后序章节将会全面分析源码,同志们,Action!