概述
MyBatis是大家最熟悉的ORM框架,大家基本都会用,那如果面试官问到MyBatis的实现原理该如何回答呢?本文将带大家过一下MyBatis的源码,好对MyBatis有一个更深刻的认识。
MyBatis的基本操作
先带大家过一下MyBatis的使用过程,这里是没有整合Spring,就是纯粹的MyBatis。
1)创建表:
drop table if exists user;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
drop table if exists orders;
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '下单用户id',
`number` varchar(32) NOT NULL COMMENT '订单号',
`createtime` datetime NOT NULL COMMENT '创建订单时间',
`note` varchar(100) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
KEY `FK_orders_1` (`user_id`),
CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'王五',NULL,'2',NULL),(10,'张三','2014-07-10','1','北京市'),(16,'张小明',NULL,'1','河南郑州'),(22,'陈小明',NULL,'1','河南郑州'),(24,'张三丰',NULL,'1','河南郑州'),(25,'陈小明',NULL,'1','河南郑州'),(26,'王五',NULL,NULL,NULL);
insert into `orders`(`id`,`user_id`,`number`,`createtime`,`note`) values (3,1,'1000010','2015-02-04 13:22:35',NULL),(4,1,'1000011','2015-02-03 13:22:41',NULL),(5,10,'1000012','2015-02-12 16:13:23',NULL);
2)添加Maven依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
3)jdbc配置文件:
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=UTF-8&useSSL=true
username=root
password=123456
4)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>
<properties resource="jdbc.properties"></properties>
<environments default="develop">
<environment id="develop">
<transactionManager type="JDBC"></transactionManager>
<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>
<!--<package name="com.qf.mbs.mapper"/>-->
<mapper resource="com/qf/mbs/mapper/UserDAO.xml"/>
<mapper resource="com/qf/mbs/mapper/OrderDAO.xml"/>
</mappers>
</configuration>
5)添加DAO接口:
public interface UserDAO {
List<User> findAll();
User findById(Integer id);
void addUser(User user);
void updateUser(User user);
void deleteUser(Integer id);
}
public interface OrderDAO {
List<Order> findAll();
List<Order> findByMap(Map<String,String> where);
}
6)添加映射文件:
<?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.qf.mbs.dao.UserDAO">
<insert id="addUser" parameterType="com.qf.mbs.po.User">
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO USER (USERNAME,BIRTHDAY,SEX,ADDRESS) VALUES (#{username},#{birthday},#{sex},#{address})
</insert>
<update id="updateUser" parameterType="com.qf.mbs.po.User">
UPDATE USER set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>
<delete id="deleteUser" parameterType="java.lang.Integer">
DELETE FROM USER where id=#{id}
</delete>
<select id="findById" parameterType="java.lang.Integer" resultType="com.qf.mbs.po.User">
SELECT * FROM USER where id=#{id}
</select>
<select id="findAll" resultType="com.qf.mbs.po.User">
select * from user
</select>
</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="com.qf.mbs.dao.OrderDAO">
<resultMap id="OrderMap" type="com.qf.mbs.po.Order">
<id property="id" column="id"/>
<result property="number" column="number"/>
<result property="createtime" column="createtime"/>
<result property="note" column="note"/>
<association property="user" javaType="com.qf.mbs.po.User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
</association>
</resultMap>
<select id="findAll" resultMap="OrderMap">
select * from orders o inner join user u on o.user_id = u.id
</select>
<select id="findByMap" resultMap="OrderMap">
select * from orders o inner join user u on o.user_id = u.id
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="number != null">
AND number = #{number}
</if>
</where>
</select>
</mapper>
7) 单元测试:
public class Test1 {
SqlSessionFactory factory = null;
{
try {
factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("config.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testAddUser() {
SqlSession sqlSession = factory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
userDAO.addUser(new User(1,"张大四","1999-9-9","男","wuhan"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void testFindAll(){
SqlSession sqlSession = factory.openSession();
OrderDAO orderDAO = sqlSession.getMapper(OrderDAO.class);
List<Order> orders = orderDAO.findAll();
System.out.println(orders);
sqlSession.close();
}
@Test
public void testFindMap(){
SqlSession sqlSession = factory.openSession();
OrderDAO orderDAO = sqlSession.getMapper(OrderDAO.class);
Map<String,String> where = new HashMap<>();
where.put("username","王五");
where.put("number","1000010");
List<Order> orders = orderDAO.findByMap(where);
System.out.println(orders);
sqlSession.close();
}
}
源码分析
接下来,我们从基本的MyBatis操作,看看MyBatis是如何完成一个数据库操作的。
首先,创建SqlSessionFactoryBuilder对象,读取配置文件,然后创建DefaultSqlSessionFactory对象。
源码如下:
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
//通过XMLConfigBuilder解析配置文件,封装为Configuration对象
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
//创建DefaultSessionFactory对象
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.
}
}
}
//build方法
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
获得SqlSessionFactory对象之后,通过openSession获得SsqlSession。
源码如下:
private SqlSession openSessionFromDataSource(ExecutorType execType,
TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
//获得配置的环境
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory =
getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level,
autoCommit);
//创建一个执行器去执行SQL命令
final Executor executor = configuration.newExecutor(tx, execType);
//返回DefaultSqlSession对象
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
我们操作数据库时需要先定义一个DAO的接口,然后通过SqlSession的getMapper获得该接口的实现,那么这个接口是如何实现的呢?
通过SqlSession从Configuration中获取。
源码如下:
DefaultSqlSession:
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
Configuration:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
MapperRegistry:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//获得一个代理工厂
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
//通过代理工厂创建代理
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
MapperProxyFactory:
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
//最后就是使用动态代理实现了DAO接口
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
然后动态代理是如何执行SQL命令的呢,看代码:
MapperProxy:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
//主要是这里执行映射的方法
return mapperMethod.execute(sqlSession, args);
}
MapperMethod:
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
//这边就是判断SQL的类型,然后分别执行增删改查的操作
if (SqlCommandType.INSERT == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
} else if (SqlCommandType.UPDATE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
} else if (SqlCommandType.DELETE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
} else if (SqlCommandType.SELECT == command.getType()) {
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
} else {
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
看一下selectList的实现:
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
//交给执行器区执行SQL
return executor.query(ms, wrapCollection(parameter),
rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
Executor有多种实现,看看SimpleExecutor:
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
//用JDBC的Statement去执行命令了
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
query方法的实现:
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
//获得PreparedStatement,执行命令
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();
//结果由ResultSetHandler 处理
return resultSetHandler.<E> handleResultSets(ps);
}
总结
最后我们梳理一下MyBatis整个执行过程:
- 通过SQLSessionFactoryBuilder创建SQLSessionFactory时,将核心配置文件中configuration节点的内容,解析到SQLSessionFactory中
- 通过SQLSessionFactory获得SqlSession时,返回DefaultSqlSession
- 调用SQLSessionFactory的getMapper方法时,返回了Mapper接口的动态代理对象,代理对象在invoke方法中实现了增删改查操作
- 具体的增删改查操作通过JDBC的Statement接口实现
本文就到这里了,如果对你有用的话,就点个赞吧:)
大家如果需要学习其他Java知识点,戳这里 超详细的Java知识点汇总