做者:小傅哥
博客:bugstack.cnhtml
沉淀、分享、成长,让本身和他人都能有所收获!😄java
Mybatis
最核心的原理也是它最便于使用的体现,为何这说?node
由于咱们在使用 Mybatis 的时候,只须要定义一个不须要写实现类的接口,就能经过注解或者配置SQL语句的方式,对数据库进行 CRUD 操做。mysql
那么这是怎么作到的呢,其中有一点很是重要,就是在 Spring 中能够把你的代理对象交给 Spring 容器,这个代理对象就是能够当作是 DAO 接口的具体实现类,而这个被代理的实现类就能够完成对数据库的一个操做,也就是这个封装过程被称为 ORM 框架。git
说了基本的流程,咱们来作点测试,让你们能够动手操做起来!学知识,必定是上手,才能获得!你能够经过如下源码仓库进行练习github
按照这个实现方式,咱们来操做一下,看看一个 Bean 的注册过程在代码中是如何实现的。面试
public interface IUserDao {
String queryUserInfo();
}
复制代码
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class<?>[] classes = {IUserDao.class};
InvocationHandler handler = (proxy, method, args) -> "你被代理了 " + method.getName();
IUserDao userDao = (IUserDao) Proxy.newProxyInstance(classLoader, classes, handler);
String res = userDao.queryUserInfo();
logger.info("测试结果:{}", res);
复制代码
Proxy.newProxyInstance
。public class ProxyBeanFactory implements FactoryBean {
@Override
public Object getObject() throws Exception {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class[] classes = {IUserDao.class};
InvocationHandler handler = (proxy, method, args) -> "你被代理了 " + method.getName();
return Proxy.newProxyInstance(classLoader, classes, handler);
}
@Override
public Class<?> getObjectType() {
return IUserDao.class;
}
}
复制代码
public class RegisterBeanFactory implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(ProxyBeanFactory.class);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(beanDefinition, "userDao");
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}
}
复制代码
在 Spring 的 Bean 管理中,全部的 Bean 最终都会被注册到类 DefaultListableBeanFactory 中,以上这部分代码主要的内容包括:spring
setBeanClass(ProxyBeanFactory.class)
。在上面咱们已经把自定义代理的 Bean 注册到了 Spring 容器中,接下来咱们来测试下这个代理的 Bean 被如何调用。sql
<bean id="userDao" class="org.itstack.interview.bean.RegisterBeanFactory"/>
复制代码
@Test
public void test_IUserDao() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml");
IUserDao userDao = beanFactory.getBean("userDao", IUserDao.class);
String res = userDao.queryUserInfo();
logger.info("测试结果:{}", res);
}
复制代码
测试结果
22:53:14.759 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
22:53:14.760 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userDao'
22:53:14.796 [main] INFO org.itstack.interview.test.ApiTest - 测试结果:你被代理了 queryUserInfo
Process finished with exit code 0
复制代码
扩展上一篇源码分析工程;itstack-demo-mybatis,增长 like 包,模仿 Mybatis 工程。完整规程下载 github.com/fuzhengwei/…
itstack-demo-mybatis
└── src
├── main
│ ├── java
│ │ └── org.itstack.demo
│ │ ├── dao
│ │ │ ├── ISchool.java
│ │ │ └── IUserDao.java
│ │ ├── like
│ │ │ ├── Configuration.java
│ │ │ ├── DefaultSqlSession.java
│ │ │ ├── DefaultSqlSessionFactory.java
│ │ │ ├── Resources.java
│ │ │ ├── SqlSession.java
│ │ │ ├── SqlSessionFactory.java
│ │ │ ├── SqlSessionFactoryBuilder.java
│ │ │ └── SqlSessionFactoryBuilder.java
│ │ └── interfaces
│ │ ├── School.java
│ │ └── User.java
│ ├── resources
│ │ ├── mapper
│ │ │ ├── School_Mapper.xml
│ │ │ └── User_Mapper.xml
│ │ ├── props
│ │ │ └── jdbc.properties
│ │ ├── spring
│ │ │ ├── mybatis-config-datasource.xml
│ │ │ └── spring-config-datasource.xml
│ │ ├── logback.xml
│ │ ├── mybatis-config.xml
│ │ └── spring-config.xml
│ └── webapp
│ └── WEB-INF
└── test
└── java
└── org.itstack.demo.test
├── ApiLikeTest.java
├── MybatisApiTest.java
└── SpringApiTest.java
复制代码
关于整个 Demo 版本,并非把全部 Mybatis 所有实现一遍,而是拨丝抽茧将最核心的内容展现给你,从使用上你会感觉如出一辙,可是实现类已经所有被替换,核心类包括;
ApiLikeTest.test_queryUserInfoById()
@Test
public void test_queryUserInfoById() {
String resource = "spring/mybatis-config-datasource.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
try {
User user = session.selectOne("org.itstack.demo.dao.IUserDao.queryUserInfoById", 1L);
System.out.println(JSON.toJSONString(user));
} finally {
session.close();
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
复制代码
一切顺利结果以下(新人每每会遇到各类问题);
{"age":18,"createTime":1576944000000,"id":1,"name":"水水","updateTime":1576944000000}
Process finished with exit code 0
复制代码
可能乍一看这测试类彻底和 MybatisApiTest.java 测试的代码如出一辙呀,也看不出区别。其实他们的引入的包是不同;
MybatisApiTest.java 里面引入的包
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
复制代码
ApiLikeTest.java 里面引入的包
import org.itstack.demo.like.Resources;
import org.itstack.demo.like.SqlSession;
import org.itstack.demo.like.SqlSessionFactory;
import org.itstack.demo.like.SqlSessionFactoryBuilder;
复制代码
好!接下来咱们开始分析这部分核心代码。
这里咱们采用 mybatis 的配置文件结构进行解析,在不破坏原有结构的状况下,最大可能的贴近源码。mybatis 单独使用的使用的时候使用了两个配置文件;数据源配置、Mapper 映射配置,以下;
mybatis-config-datasource.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="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/itstack?useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/User_Mapper.xml"/>
<mapper resource="mapper/School_Mapper.xml"/>
</mappers>
</configuration>
复制代码
User_Mapper.xml & Mapper 映射配置
<?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.itstack.demo.dao.IUserDao">
<select id="queryUserInfoById" parameterType="java.lang.Long" resultType="org.itstack.demo.po.User">
SELECT id, name, age, createTime, updateTime
FROM user
where id = #{id}
</select>
<select id="queryUserList" parameterType="org.itstack.demo.po.User" resultType="org.itstack.demo.po.User">
SELECT id, name, age, createTime, updateTime
FROM user
where age = #{age}
</select>
</mapper>
复制代码
这里的加载过程与 mybaits 不一样,咱们采用 dom4j 方式。在案例中会看到最开始获取资源,以下;
ApiLikeTest.test_queryUserInfoById() & 部分截取
String resource = "spring/mybatis-config-datasource.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(resource);
...
复制代码
从上能够看到这是经过配置文件地址获取到了读取流的过程,从而为后面解析作基础。首先咱们先看 Resources 类,整个是咱们的资源类。
Resources.java & 资源类
/** * 博 客 | https://bugstack.cn * Create by 小傅哥 @2020 */
public class Resources {
public static Reader getResourceAsReader(String resource) throws IOException {
return new InputStreamReader(getResourceAsStream(resource));
}
private static InputStream getResourceAsStream(String resource) throws IOException {
ClassLoader[] classLoaders = getClassLoaders();
for (ClassLoader classLoader : classLoaders) {
InputStream inputStream = classLoader.getResourceAsStream(resource);
if (null != inputStream) {
return inputStream;
}
}
throw new IOException("Could not find resource " + resource);
}
private static ClassLoader[] getClassLoaders() {
return new ClassLoader[]{
ClassLoader.getSystemClassLoader(),
Thread.currentThread().getContextClassLoader()};
}
}
复制代码
这段代码方法的入口是getResourceAsReader,直到往下以此作了;
配置文件加载后开始进行解析操做,这里咱们也仿照 mybatis 但进行简化,以下;
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
复制代码
SqlSessionFactoryBuilder.build() & 入口构建类
public DefaultSqlSessionFactory build(Reader reader) {
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new InputSource(reader));
Configuration configuration = parseConfiguration(document.getRootElement());
return new DefaultSqlSessionFactory(configuration);
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
复制代码
SqlSessionFactoryBuilder.parseConfiguration() & 解析过程
private Configuration parseConfiguration(Element root) {
Configuration configuration = new Configuration();
configuration.setDataSource(dataSource(root.selectNodes("//dataSource")));
configuration.setConnection(connection(configuration.dataSource));
configuration.setMapperElement(mapperElement(root.selectNodes("mappers")));
return configuration;
}
复制代码
SqlSessionFactoryBuilder.dataSource() & 解析出数据源
private Map<String, String> dataSource(List<Element> list) {
Map<String, String> dataSource = new HashMap<>(4);
Element element = list.get(0);
List content = element.content();
for (Object o : content) {
Element e = (Element) o;
String name = e.attributeValue("name");
String value = e.attributeValue("value");
dataSource.put(name, value);
}
return dataSource;
}
复制代码
SqlSessionFactoryBuilder.connection() & 获取数据库链接
private Connection connection(Map<String, String> dataSource) {
try {
Class.forName(dataSource.get("driver"));
return DriverManager.getConnection(dataSource.get("url"), dataSource.get("username"), dataSource.get("password"));
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return null;
}
复制代码
SqlSessionFactoryBuilder.mapperElement() & 解析SQL语句
private Map<String, XNode> mapperElement(List<Element> list) {
Map<String, XNode> map = new HashMap<>();
Element element = list.get(0);
List content = element.content();
for (Object o : content) {
Element e = (Element) o;
String resource = e.attributeValue("resource");
try {
Reader reader = Resources.getResourceAsReader(resource);
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new InputSource(reader));
Element root = document.getRootElement();
//命名空间
String namespace = root.attributeValue("namespace");
// SELECT
List<Element> selectNodes = root.selectNodes("select");
for (Element node : selectNodes) {
String id = node.attributeValue("id");
String parameterType = node.attributeValue("parameterType");
String resultType = node.attributeValue("resultType");
String sql = node.getText();
// ? 匹配
Map<Integer, String> parameter = new HashMap<>();
Pattern pattern = Pattern.compile("(#\\{(.*?)})");
Matcher matcher = pattern.matcher(sql);
for (int i = 1; matcher.find(); i++) {
String g1 = matcher.group(1);
String g2 = matcher.group(2);
parameter.put(i, g2);
sql = sql.replace(g1, "?");
}
XNode xNode = new XNode();
xNode.setNamespace(namespace);
xNode.setId(id);
xNode.setParameterType(parameterType);
xNode.setResultType(resultType);
xNode.setSql(sql);
xNode.setParameter(parameter);
map.put(namespace + "." + id, xNode);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return map;
}
复制代码
最后将初始化后的配置类 Configuration,做为参数进行建立 DefaultSqlSessionFactory,以下;
public DefaultSqlSessionFactory build(Reader reader) {
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new InputSource(reader));
Configuration configuration = parseConfiguration(document.getRootElement());
return new DefaultSqlSessionFactory(configuration);
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
复制代码
DefaultSqlSessionFactory.java & SqlSessionFactory的实现类
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private final Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration.connection, configuration.mapperElement);
}
}
复制代码
SqlSession session = sqlMapper.openSession();
复制代码
上面这一步就是建立了DefaultSqlSession,比较简单。以下;
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration.connection, configuration.mapperElement);
}
复制代码
User user = session.selectOne("org.itstack.demo.dao.IUserDao.queryUserInfoById", 1L);
复制代码
在 DefaultSqlSession 中经过实现 SqlSession,提供数据库语句查询和关闭链接池,以下;
SqlSession.java & 定义
public interface SqlSession {
<T> T selectOne(String statement);
<T> T selectOne(String statement, Object parameter);
<T> List<T> selectList(String statement);
<T> List<T> selectList(String statement, Object parameter);
void close();
}
复制代码
接下来看具体的执行过程,session.selectOne
DefaultSqlSession.selectOne() & 执行查询
public <T> T selectOne(String statement, Object parameter) {
XNode xNode = mapperElement.get(statement);
Map<Integer, String> parameterMap = xNode.getParameter();
try {
PreparedStatement preparedStatement = connection.prepareStatement(xNode.getSql());
buildParameter(preparedStatement, parameter, parameterMap);
ResultSet resultSet = preparedStatement.executeQuery();
List<T> objects = resultSet2Obj(resultSet, Class.forName(xNode.getResultType()));
return objects.get(0);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
复制代码
selectOne 就objects.get(0);,selectList 就所有返回
经过 statement 获取最初解析 xml 时候的存储的 select 标签信息;
<select id="queryUserInfoById" parameterType="java.lang.Long" resultType="org.itstack.demo.po.User">
SELECT id, name, age, createTime, updateTime
FROM user
where id = #{id}
</select>
复制代码
获取 sql 语句后交给 jdbc 的 PreparedStatement 类进行执行
这里还须要设置入参,咱们将入参设置进行抽取,以下;
private void buildParameter(PreparedStatement preparedStatement, Object parameter, Map<Integer, String> parameterMap) throws SQLException, IllegalAccessException {
int size = parameterMap.size();
// 单个参数
if (parameter instanceof Long) {
for (int i = 1; i <= size; i++) {
preparedStatement.setLong(i, Long.parseLong(parameter.toString()));
}
return;
}
if (parameter instanceof Integer) {
for (int i = 1; i <= size; i++) {
preparedStatement.setInt(i, Integer.parseInt(parameter.toString()));
}
return;
}
if (parameter instanceof String) {
for (int i = 1; i <= size; i++) {
preparedStatement.setString(i, parameter.toString());
}
return;
}
Map<String, Object> fieldMap = new HashMap<>();
// 对象参数
Field[] declaredFields = parameter.getClass().getDeclaredFields();
for (Field field : declaredFields) {
String name = field.getName();
field.setAccessible(true);
Object obj = field.get(parameter);
field.setAccessible(false);
fieldMap.put(name, obj);
}
for (int i = 1; i <= size; i++) {
String parameterDefine = parameterMap.get(i);
Object obj = fieldMap.get(parameterDefine);
if (obj instanceof Short) {
preparedStatement.setShort(i, Short.parseShort(obj.toString()));
continue;
}
if (obj instanceof Integer) {
preparedStatement.setInt(i, Integer.parseInt(obj.toString()));
continue;
}
if (obj instanceof Long) {
preparedStatement.setLong(i, Long.parseLong(obj.toString()));
continue;
}
if (obj instanceof String) {
preparedStatement.setString(i, obj.toString());
continue;
}
if (obj instanceof Date) {
preparedStatement.setDate(i, (java.sql.Date) obj);
}
}
}
复制代码
设置参数后执行查询 preparedStatement.executeQuery()
接下来须要将查询结果转换为咱们的类(主要是反射类的操做),resultSet2Obj(resultSet, Class.forName(xNode.getResultType()));
private <T> List<T> resultSet2Obj(ResultSet resultSet, Class<?> clazz) {
List<T> list = new ArrayList<>();
try {
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
// 每次遍历行值
while (resultSet.next()) {
T obj = (T) clazz.newInstance();
for (int i = 1; i <= columnCount; i++) {
Object value = resultSet.getObject(i);
String columnName = metaData.getColumnName(i);
String setMethod = "set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1);
Method method;
if (value instanceof Timestamp) {
method = clazz.getMethod(setMethod, Date.class);
} else {
method = clazz.getMethod(setMethod, value.getClass());
}
method.invoke(obj, value);
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
复制代码
sql 查询有入参、有不须要入参、有查询一个、有查询集合,只须要合理包装便可,例以下面的查询集合,入参是对象类型;
ApiLikeTest.test_queryUserList()
@Test
public void test_queryUserList() {
String resource = "spring/mybatis-config-datasource.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
try {
User req = new User();
req.setAge(18);
List<User> userList = session.selectList("org.itstack.demo.dao.IUserDao.queryUserList", req);
System.out.println(JSON.toJSONString(userList));
} finally {
session.close();
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
复制代码
**测试结果:
[{"age":18,"createTime":1576944000000,"id":1,"name":"水水","updateTime":1576944000000},{"age":18,"createTime":1576944000000,"id":2,"name":"豆豆","updateTime":1576944000000}]
Process finished with exit code 0
复制代码
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
复制代码
Mybatis的整个源码仍是很大的,如下主要将部分核心内容进行整理分析,以便于后续分析Mybatis与Spring整合的源码部分。简要包括;容器初始化、配置文件解析、Mapper加载与动态代理。
要学习Mybatis源码,最好的方式必定是从一个简单的点进入,而不是从Spring整合开始分析。SqlSessionFactory是整个Mybatis的核心实例对象,SqlSessionFactory对象的实例又经过SqlSessionFactoryBuilder对象来得到。SqlSessionFactoryBuilder对象能够从XML配置文件加载配置信息,而后建立SqlSessionFactory。以下例子:
MybatisApiTest.java
public class MybatisApiTest {
@Test
public void test_queryUserInfoById() {
String resource = "spring/mybatis-config-datasource.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
try {
User user = session.selectOne("org.itstack.demo.dao.IUserDao.queryUserInfoById", 1L);
System.out.println(JSON.toJSONString(user));
} finally {
session.close();
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
复制代码
dao/IUserDao.java
public interface IUserDao {
User queryUserInfoById(Long id);
}
复制代码
spring/mybatis-config-datasource.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="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/itstack?useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/User_Mapper.xml"/>
</mappers>
</configuration>
复制代码
若是一切顺利,那么会有以下结果:
{"age":18,"createTime":1571376957000,"id":1,"name":"花花","updateTime":1571376957000}
复制代码
从上面的代码块能够看到,核心代码;SqlSessionFactoryBuilder().build(reader),负责Mybatis配置文件的加载、解析、构建等职责,直到最终能够经过SqlSession来执行并返回结果。
从上面代码能够看到,SqlSessionFactory是经过SqlSessionFactoryBuilder工厂类建立的,而不是直接使用构造器。容器的配置文件加载和初始化流程以下:
SqlSessionFactoryBuilder.java
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(Reader reader) {
return build(reader, null, null);
}
public SqlSessionFactory build(Reader reader, String environment) {
return build(reader, environment, null);
}
public SqlSessionFactory build(Reader reader, Properties properties) {
return build(reader, null, properties);
}
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}
public SqlSessionFactory build(InputStream inputStream, String environment) {
return build(inputStream, environment, null);
}
public SqlSessionFactory build(InputStream inputStream, Properties properties) {
return build(inputStream, null, properties);
}
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
}
复制代码
从上面的源码能够看到,SqlSessionFactory提供三种方式build构建对象;
那么,字节流、字符流都会建立配置文件解析类:XMLConfigBuilder,并经过parser.parse()生成Configuration,最后调用配置类构建方法生成SqlSessionFactory。
XMLConfigBuilder.java
public class XMLConfigBuilder extends BaseBuilder {
private boolean parsed;
private final XPathParser parser;
private String environment;
private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
...
public XMLConfigBuilder(Reader reader, String environment, Properties props) {
this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
}
...
}
复制代码
XMLMapperEntityResolver.java
public class XMLMapperEntityResolver implements EntityResolver {
private static final String IBATIS_CONFIG_SYSTEM = "ibatis-3-config.dtd";
private static final String IBATIS_MAPPER_SYSTEM = "ibatis-3-mapper.dtd";
private static final String MYBATIS_CONFIG_SYSTEM = "mybatis-3-config.dtd";
private static final String MYBATIS_MAPPER_SYSTEM = "mybatis-3-mapper.dtd";
private static final String MYBATIS_CONFIG_DTD = "org/apache/ibatis/builder/xml/mybatis-3-config.dtd";
private static final String MYBATIS_MAPPER_DTD = "org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd";
/* * Converts a public DTD into a local one * * @param publicId The public id that is what comes after "PUBLIC" * @param systemId The system id that is what comes after the public id. * @return The InputSource for the DTD * * @throws org.xml.sax.SAXException If anything goes wrong */
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
try {
if (systemId != null) {
String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
if (lowerCaseSystemId.contains(MYBATIS_CONFIG_SYSTEM) || lowerCaseSystemId.contains(IBATIS_CONFIG_SYSTEM)) {
return getInputSource(MYBATIS_CONFIG_DTD, publicId, systemId);
} else if (lowerCaseSystemId.contains(MYBATIS_MAPPER_SYSTEM) || lowerCaseSystemId.contains(IBATIS_MAPPER_SYSTEM)) {
return getInputSource(MYBATIS_MAPPER_DTD, publicId, systemId);
}
}
return null;
} catch (Exception e) {
throw new SAXException(e.toString());
}
}
private InputSource getInputSource(String path, String publicId, String systemId) {
InputSource source = null;
if (path != null) {
try {
InputStream in = Resources.getResourceAsStream(path);
source = new InputSource(in);
source.setPublicId(publicId);
source.setSystemId(systemId);
} catch (IOException e) {
// ignore, null is ok
}
}
return source;
}
}
复制代码
XPathParser.java
public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {
commonConstructor(validation, variables, entityResolver);
this.document = createDocument(new InputSource(reader));
}
private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {
this.validation = validation;
this.entityResolver = entityResolver;
this.variables = variables;
XPathFactory factory = XPathFactory.newInstance();
this.xpath = factory.newXPath();
}
private Document createDocument(InputSource inputSource) {
// important: this must only be called AFTER common constructor
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validation);
factory.setNamespaceAware(false);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(false);
factory.setCoalescing(false);
factory.setExpandEntityReferences(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(entityResolver);
builder.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
}
});
return builder.parse(inputSource);
} catch (Exception e) {
throw new BuilderException("Error creating document instance. Cause: " + e, e);
}
}
复制代码
从上到下能够看到主要是为了建立一个Mybatis的文档解析器,最后根据builder.parse(inputSource)返回Document
获得XPathParser实例后,接下来在调用方法:this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
XMLConfigBuilder.this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
super(new Configuration());
ErrorContext.instance().resource("SQL Mapper Configuration");
this.configuration.setVariables(props);
this.parsed = false;
this.environment = environment;
this.parser = parser;
}
复制代码
其中调用了父类的构造函数
public abstract class BaseBuilder {
protected final Configuration configuration;
protected final TypeAliasRegistry typeAliasRegistry;
protected final TypeHandlerRegistry typeHandlerRegistry;
public BaseBuilder(Configuration configuration) {
this.configuration = configuration;
this.typeAliasRegistry = this.configuration.getTypeAliasRegistry();
this.typeHandlerRegistry = this.configuration.getTypeHandlerRegistry();
}
}
复制代码
XMLConfigBuilder建立完成后,sqlSessionFactoryBuild调用parser.parse()建立Configuration
public class XMLConfigBuilder extends BaseBuilder {
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
}
复制代码
这一部分是整个XML文件解析和装载的核心内容,其中包括;
parseConfiguration(parser.evalNode("/configuration"));
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
//属性解析propertiesElement
propertiesElement(root.evalNode("properties"));
//加载settings节点settingsAsProperties
Properties settings = settingsAsProperties(root.evalNode("settings"));
//加载自定义VFS loadCustomVfs
loadCustomVfs(settings);
//解析类型别名typeAliasesElement
typeAliasesElement(root.evalNode("typeAliases"));
//加载插件pluginElement
pluginElement(root.evalNode("plugins"));
//加载对象工厂objectFactoryElement
objectFactoryElement(root.evalNode("objectFactory"));
//建立对象包装器工厂objectWrapperFactoryElement
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
//加载反射工厂reflectorFactoryElement
reflectorFactoryElement(root.evalNode("reflectorFactory"));
//元素设置
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
//加载环境配置environmentsElement
environmentsElement(root.evalNode("environments"));
//数据库厂商标识加载databaseIdProviderElement
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
//加载类型处理器typeHandlerElement
typeHandlerElement(root.evalNode("typeHandlers"));
//加载mapper文件mapperElement
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
复制代码
全部的root.evalNode()底层都是调用XML DOM方法:Object evaluate(String expression, Object item, QName returnType),表达式参数expression,经过XObject resultObject = eval( expression, item )返回最终节点内容,能够参考mybatis.org/dtd/mybatis…
<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>
<!ELEMENT databaseIdProvider (property*)>
<!ATTLIST databaseIdProvider type CDATA #REQUIRED >
<!ELEMENT properties (property*)>
<!ATTLIST properties resource CDATA #IMPLIED url CDATA #IMPLIED >
<!ELEMENT property EMPTY>
<!ATTLIST property name CDATA #REQUIRED value CDATA #REQUIRED >
<!ELEMENT settings (setting+)>
<!ELEMENT setting EMPTY>
<!ATTLIST setting name CDATA #REQUIRED value CDATA #REQUIRED >
<!ELEMENT typeAliases (typeAlias*,package*)>
<!ELEMENT typeAlias EMPTY>
<!ATTLIST typeAlias type CDATA #REQUIRED alias CDATA #IMPLIED >
<!ELEMENT typeHandlers (typeHandler*,package*)>
<!ELEMENT typeHandler EMPTY>
<!ATTLIST typeHandler javaType CDATA #IMPLIED jdbcType CDATA #IMPLIED handler CDATA #REQUIRED >
<!ELEMENT objectFactory (property*)>
<!ATTLIST objectFactory type CDATA #REQUIRED >
<!ELEMENT objectWrapperFactory EMPTY>
<!ATTLIST objectWrapperFactory type CDATA #REQUIRED >
<!ELEMENT reflectorFactory EMPTY>
<!ATTLIST reflectorFactory type CDATA #REQUIRED >
<!ELEMENT plugins (plugin+)>
<!ELEMENT plugin (property*)>
<!ATTLIST plugin interceptor CDATA #REQUIRED >
<!ELEMENT environments (environment+)>
<!ATTLIST environments default CDATA #REQUIRED >
<!ELEMENT environment (transactionManager,dataSource)>
<!ATTLIST environment id CDATA #REQUIRED >
<!ELEMENT transactionManager (property*)>
<!ATTLIST transactionManager type CDATA #REQUIRED >
<!ELEMENT dataSource (property*)>
<!ATTLIST dataSource type CDATA #REQUIRED >
<!ELEMENT mappers (mapper*,package*)>
<!ELEMENT mapper EMPTY>
<!ATTLIST mapper resource CDATA #IMPLIED url CDATA #IMPLIED class CDATA #IMPLIED >
<!ELEMENT package EMPTY>
<!ATTLIST package name CDATA #REQUIRED >
复制代码
mybatis-3-config.dtd 定义文件中有11个配置文件,以下;
以上每一个配置都是可选。最终配置内容会保存到org.apache.ibatis.session.Configuration,以下;
public class Configuration {
protected Environment environment;
// 容许在嵌套语句中使用分页(RowBounds)。若是容许使用则设置为false。默认为false
protected boolean safeRowBoundsEnabled;
// 容许在嵌套语句中使用分页(ResultHandler)。若是容许使用则设置为false。
protected boolean safeResultHandlerEnabled = true;
// 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的相似映射。默认false
protected boolean mapUnderscoreToCamelCase;
// 当开启时,任何方法的调用都会加载该对象的全部属性。不然,每一个属性会按需加载。默认值false (true in ≤3.4.1)
protected boolean aggressiveLazyLoading;
// 是否容许单一语句返回多结果集(须要兼容驱动)。
protected boolean multipleResultSetsEnabled = true;
// 容许 JDBC 支持自动生成主键,须要驱动兼容。这就是insert时获取mysql自增主键/oracle sequence的开关。注:通常来讲,这是但愿的结果,应该默认值为true比较合适。
protected boolean useGeneratedKeys;
// 使用列标签代替列名,通常来讲,这是但愿的结果
protected boolean useColumnLabel = true;
// 是否启用缓存 {默认是开启的,可能这也是你的面试题}
protected boolean cacheEnabled = true;
// 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。
protected boolean callSettersOnNulls;
// 容许使用方法签名中的名称做为语句参数名称。 为了使用该特性,你的工程必须采用Java 8编译,而且加上-parameters选项。(从3.4.1开始)
protected boolean useActualParamName = true;
//当返回行的全部列都是空时,MyBatis默认返回null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集 (i.e. collectioin and association)。(从3.4.2开始) 注:这里应该拆分为两个参数比较合适, 一个用于结果集,一个用于单记录。一般来讲,咱们会但愿结果集不是null,单记录仍然是null
protected boolean returnInstanceForEmptyRow;
// 指定 MyBatis 增长到日志名称的前缀。
protected String logPrefix;
// 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。通常建议指定为slf4j或log4j
protected Class <? extends Log> logImpl;
// 指定VFS的实现, VFS是mybatis提供的用于访问AS内资源的一个简便接口
protected Class <? extends VFS> vfsImpl;
// MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种状况下会缓存一个会话中执行的全部查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不一样调用将不会共享数据。
protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
// 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动须要指定列的 JDBC 类型,多数状况直接用通常类型便可,好比 NULL、VARCHAR 或 OTHER。
protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
// 指定对象的哪一个方法触发一次延迟加载。
protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" }));
// 设置超时时间,它决定驱动等待数据库响应的秒数。默认不超时
protected Integer defaultStatementTimeout;
// 为驱动的结果集设置默认获取数量。
protected Integer defaultFetchSize;
// SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
// 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(不管是否嵌套)。
protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
// 指定发现自动映射目标未知列(或者未知属性类型)的行为。这个值应该设置为WARNING比较合适
protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
// settings下的properties属性
protected Properties variables = new Properties();
// 默认的反射器工厂,用于操做属性、构造器方便
protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
// 对象工厂, 全部的类resultMap类都须要依赖于对象工厂来实例化
protected ObjectFactory objectFactory = new DefaultObjectFactory();
// 对象包装器工厂,主要用来在建立非原生对象,好比增长了某些监控或者特殊属性的代理类
protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
// 延迟加载的全局开关。当开启时,全部关联对象都会延迟加载。特定关联关系中可经过设置fetchType属性来覆盖该项的开关状态。
protected boolean lazyLoadingEnabled = false;
// 指定 Mybatis 建立具备延迟加载能力的对象所用到的代理工具。MyBatis 3.3+使用JAVASSIST
protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
// MyBatis 能够根据不一样的数据库厂商执行不一样的语句,这种多厂商的支持是基于映射语句中的 databaseId 属性。
protected String databaseId;
...
}
复制代码
以上能够看到,Mybatis把全部的配置;resultMap、Sql语句、插件、缓存等都维护在Configuration中。这里还有一个小技巧,在Configuration还有一个StrictMap内部类,它继承于HashMap完善了put时防重、get时取不到值的异常处理,以下;
protected static class StrictMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = -4950446264854982944L;
private final String name;
public StrictMap(String name, int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
this.name = name;
}
public StrictMap(String name, int initialCapacity) {
super(initialCapacity);
this.name = name;
}
public StrictMap(String name) {
super();
this.name = name;
}
public StrictMap(String name, Map<String, ? extends V> m) {
super(m);
this.name = name;
}
}
复制代码
(核心)加载mapper文件mapperElement
Mapper文件处理是Mybatis框架的核心服务,全部的SQL语句都编写在Mapper中,这块也是咱们分析的重点,其余模块能够后续讲解。
XMLConfigBuilder.parseConfiguration()->mapperElement(root.evalNode("mappers"));
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
// 若是要同时使用package自动扫描和经过mapper明确指定要加载的mapper,必定要确保package自动扫描的范围不包含明确指定的mapper,不然在经过package扫描的interface的时候,尝试加载对应xml文件的loadXmlResource()的逻辑中出现判重出错,报org.apache.ibatis.binding.BindingException异常,即便xml文件中包含的内容和mapper接口中包含的语句不重复也会出错,包括加载mapper接口时自动加载的xml mapper也同样会出错。
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {
Class<?> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}
复制代码
Mybatis提供了两类配置Mapper的方法,第一类是使用package自动搜索的模式,这样指定package下全部接口都会被注册为mapper,也是在Spring中比较经常使用的方式,例如:
<mappers>
<package name="org.itstack.demo"/>
</mappers>
复制代码
另一类是明确指定Mapper,这又能够经过resource、url或者class进行细分,例如;
<mappers>
<mapper resource="mapper/User_Mapper.xml"/>
<mapper class=""/>
<mapper url=""/>
</mappers>
复制代码
经过package方式自动搜索加载,生成对应的mapper代理类,代码块和流程,以下;
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
...
}
}
}
}
复制代码
Mapper加载到生成代理对象的流程中,主要的核心类包括;
MapperRegistry.java
解析加载Mapper
public void addMappers(String packageName, Class<?> superType) {
// mybatis框架提供的搜索classpath下指定package以及子package中符合条件(注解或者继承于某个类/接口)的类,默认使用Thread.currentThread().getContextClassLoader()返回的加载器,和spring的工具类异曲同工。
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
// 无条件的加载全部的类,由于调用方传递了Object.class做为父类,这也给之后的指定mapper接口预留了余地
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
// 全部匹配的calss都被存储在ResolverUtil.matches字段中
Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
for (Class<?> mapperClass : mapperSet) {
//调用addMapper方法进行具体的mapper类/接口解析
addMapper(mapperClass);
}
}
复制代码
生成代理类:MapperProxyFactory
public <T> void addMapper(Class<T> type) {
// 对于mybatis mapper接口文件,必须是interface,不能是class
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
// 为mapper接口建立一个MapperProxyFactory代理
knownMappers.put(type, new MapperProxyFactory<T>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
复制代码
在MapperRegistry中维护了接口类与代理工程的映射关系,knownMappers;
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
复制代码
MapperProxyFactory.java
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}
复制代码
如上是Mapper的代理类工程,构造函数中的mapperInterface就是对应的接口类,当实例化时候会得到具体的MapperProxy代理,里面主要包含了SqlSession。