概要
我们都知道,mybatis框架是一个半自动的ORM框架,可以简化我们对于数据库连接的管理,以及可以对于所有的查询配置的统一维护。是对于传统的JDBC连接操作的二次封装。
传统的JDBC获取数据
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection collection = null;
Statement statement = null;
ResultSet resultSet = null;
Class.forName("com.mysql.jdbc.Driver");
try {
//获取数据库连接
collection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8",
"root", "root");
statement = collection.createStatement();
resultSet = statement.executeQuery("select * from t_stu");
while (resultSet.next()) {
System.out.println(resultSet.getString("name"));
}
} finally {
//关闭数据库的资源
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (collection != null) {
collection.close();
}
}
}
这样其实我们都需要手动的获取连接数据,关闭流数据。于是我们发现了很多问题如,例如:
- 数据库的连接需要业务方去维护,而且mysql的连接每次使用都需要新建
- sql代码和我们的业务代码耦合到一块,当一个sql很复杂的时候很难维护
- sql当中的参数维护需要人为去管理,当一个逻辑很复杂时会出现很多的参数,造成难以维护的情况
- sql查询后返回的结果需要我们手动去关联,而且没有统一的管理的入口
为了解决上面的一系列问题,聪明的程序员对通用的代码逻辑进行了抽象与封装,于是ORM框架在万众举目当中出现了,mybatis就是其中的一个
通过Mybatis框架获取数据
为了解决上面的一些列问题,mybatis引入了一系列的组件来解决出现的问题。
- 为了解决业务方手动维护连接的问题,引入了连接池,mybatis的默认连接池是c3p0,后续出现了很多性能更高的连接池可用来替换,如:hikaricp
- 为了解决对于每个表的sql查询的维护,引入了Mapper文件,每个表的查询语句都可以放入到一个对应的Mapper
- 为了解决查询参数和影响结果的映射,通过反射的方式将查询结果映射到具体对象当中
mybatis的查询基于对查询的SqlSession封装
- SqlSessionFactory的创建过程,会解析我们配置xml数据,最终将xml数据解析成为org.apache.ibatis.session.Configuration对象传递给SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream("classPath:mybatis-config.xml"));
- 当我们在获取一个sqlSession,会通过默认的DefaultSqlSessionFactory.openSessionFromDataSource获取
SqlSession sqlSession=sqlSessionFactory.openSession();
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
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);
//生成一个执行器
final Executor executor = configuration.newExecutor(tx, execType);
//new一个默认的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();
}
}
- 通过sqlSession获取我们调用的xxxMapper或者xxxDao的代理对象,sqlSession.getMapper(xxx.class),根据代理对象最终来查询我们的sql;
//1 通过DefaultSqlSession获取配置信息,获取已注册的MapperProxy
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
//2 通过MapperProxyFactory获取mapperProxy
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);
}
}
//3.通过反射获取最终可执行的MapperProxy
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
//通过JDK动态代理生成反射对象
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
小结
通过对源码的分析,我们大概了解到myabatis从解析配置文件到最终获取一个xxxMapper或xxxDao代理对象的整个流程