SqlSessionFactoryBuilder
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties)
这个方法有多个重载,reader参数可以用流的形式(字节、字符)来告诉SqlSessionFactoryBuilder加载哪个Mybatis配置文件。
environment参数引用了Mybatis配置文件中的<environment>元素的数据库配置,如果不指定该参数,则加载<environments>的default属性值。
properties参数用于为Mybatis配置文件传入额外的属性配置。
build()的重载方法
public SqlSessionFactory build(InputStream inputStream)
public SqlSessionFactory build(InputStream inputStream, String environment)
public SqlSessionFactory build(InputStream inputStream, Properties properties)
public SqlSessionFactory build(Reader reader, String environment)
public SqlSessionFactory build(Reader reader, Properties properties)
public SqlSessionFactory build(Reader reader, String environment, Properties properties)
注意:一旦SqlSessionFactory对象创建成功,就再也不需要SqlSessionFactoryBuilder了。因此最好用局部变量的SqlSessionFactoryBuilder来创建SqlSessionFactory,这样能保证它被尽快销毁,释放它用到的XMLConfigBuilder和XML资源
SqlSessionFactory
主要使用它的openSession()方法来获取SqlSession,它提供了几个重载的openSession()方法
SqlSession openSession();
SqlSession openSession(boolean autoCommit);
SqlSession openSession(Connection connection);
SqlSession openSession(TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType);
SqlSession openSession(ExecutorType execType, boolean autoCommit);
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType, Connection connection);
autoCommit参数负责事务处理,将其设为false,不是用自动提交,而使用显式的事务控制,这也是Mybatis推荐的方式
connection参数可以显式传入用户提供的Connection对象,不传入则Mybatis会使用配置的数据源获取连接
execType参数可以控制Mybatis底层是否复用PreparedStatement,是否使用JDBC的批量更新
level则控制隔离级别
openSession()不传入参数
不自动提交
使用底层数据源配置获取连接
PreparedStatement既不复用也不启用批量更新,相当于为execType传入Executor.SIMPLE值
execType参数支持三个值:
ExecutorType.SIMPLE既不复用也不启用批量更新
ExecutorType.REUSE复用PreparedStatement
ExecutorType.BATCH启用批量更新
SqlSession
它是Mybatis执行数据库操作的最核心的API,不过Mybatis并不推荐直接使用SqlSession里面的insert()、update()、delete()执行数据库操作。
其他的不论,批量更新应该说一说
SqlSession提供了批量更新的方法,不过要在获取SqlSession的时候将execType参数传ExecutorType.BATCH
比较两种不同的方式(Executor.SIMPLE和BATCH方式)插入500条数据的速度
运行结果分别为:
当然了,插入次数如果足够多的话可能会更快
如果数据库本身支持批量插入,则建议使用Mybatis的foreach元素利用这个特性,这种来自数据库底层支持的批量插入肯定具有更好的性能