Mybatis核心API的一些东西

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元素利用这个特性,这种来自数据库底层支持的批量插入肯定具有更好的性能

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

服务端相声演员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值