mybatis操作数据库 - 969251639/study GitHub Wiki

mytatis通过SqlSessionFactory这个工厂类打开会话,进而获得操作mapper的通道

public static void main(String[] args) throws IOException {
			String resource = "mybatis-config.xml";
	        InputStream inputStream = Resources.getResourceAsStream(resource);
	        //从 XML 中构建 SqlSessionFactory
	        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	        SqlSession session = sqlSessionFactory.openSession();
	        try {
	        	List<Blog> blogs = session.selectList("test.Blog.findById", 67);
	        	System.out.println(blogs);
	        	//int result = session.insert("test.Blog.add", null);
	        	//System.out.println(result);
	        	blogs = session.selectList("test.Blog.findById", 2);
	        	System.out.println(blogs);
	        	session.commit();
	        } finally {
	            session.close();
	        }
	}

sqlSessionFactory打开session后可以获取到SqlSession对象,mybatis的所有操作都是通过它进行操作。

  public SqlSessionFactory build(InputStream inputStream) {
    return build(inputStream, null, null);
  }

  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);
  }

这个SqlSession对象默认便是DefaultSqlSessionFactory,接下来看它的openSession方法

  @Override
  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);//获取一个sql执行器
      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();
    }
  }

这里包含了创建事务管理器,sql执行器(这个东西很重要,底层的sql都是需要它来操作,mybatis提供了三种执行类型SIMPLE, REUSE, BATCH,默认是SIMPLE),最后返回一个DefaultSqlSession对象进行操作

DefaultSqlSession实现了SqlSession接口,SqlSession接口定义操作mybatis的基本方法

public interface SqlSession extends Closeable {
  //查询一条数据
  <T> T selectOne(String statement);
  <T> T selectOne(String statement, Object parameter);

  //查询多条数据
  <E> List<E> selectList(String statement);
  <E> List<E> selectList(String statement, Object parameter);
  <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds);

  //查询一条数据,并包装成Map
  <K, V> Map<K, V> selectMap(String statement, String mapKey);
  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey);
  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds);

  //游标查询
  <T> Cursor<T> selectCursor(String statement);
  <T> Cursor<T> selectCursor(String statement, Object parameter);
  <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds);
  
  //自定义查询结果处理
  void select(String statement, Object parameter, ResultHandler handler);
  void select(String statement, ResultHandler handler);
  void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);

  //增删改
  int insert(String statement);
  int insert(String statement, Object parameter);
  int update(String statement);
  int update(String statement, Object parameter);
  int delete(String statement);
  int delete(String statement, Object parameter);

  //事务操作
  void commit();
  void commit(boolean force);
  void rollback();
  void rollback(boolean force);

  //flush批量操作
  List<BatchResult> flushStatements();

  //关闭连接
  @Override
  void close();

  //清空本地缓存
  void clearCache();

  //获取配置信息
  Configuration getConfiguration();

  //获取Mapper
  <T> T getMapper(Class<T> type);

  //获取连接
  Connection getConnection();
}

所以,有了DefaultSqlSession对象后就可以对数据进行各种CRUD操作了

⚠️ **GitHub.com Fallback** ⚠️