Mybatisは、理解して学習するために、一般的に使用されるオブジェクトSqlSessionFactory、SqlSessionを使用します
Mybatis依存関係パッケージ
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
Mybatisの自動組み立て手順
- 構成ファイルをロードします
- SqlSessionFactoryオブジェクトを取得します
- SqlSessionFactoryBuilderと構成ファイルストリームを取得して、SqlSessionFactoryオブジェクトを取得します
- SqlSessionFactoryオブジェクトを使用してSqlSessionを開きます
- SqlSessionを介して対応するMapperオブジェクトを取得します
- Mapperオブジェクトを介して対応するインターフェイスを呼び出し、データベースにクエリを実行します
SqlSessionFactory
- SqlSessionFactory:ファクトリデザインパターン、SqlSessionを作成するファクトリ。Mybatisのアプリケーションは、SqlSessionFactoryのインスタンスに基づいています。SqlSessionFactoryBuilderは、XML構成ファイルからインスタンスを構築するか、ConfigurationおよびSqlSessionFactory作成メソッドを使用できます。
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
- build()
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
SqlSessionFactoryの作成手順
- データソース、トランザクション、マッパーファイルリソースなどを含む構成オブジェクトを定義します。
- 構成オブジェクトを介してSqlSessionFactoryBuilderオブジェクトを作成します。
- SqlSessionFactoryBuilderを介してSqlSessionFactoryのインスタンスを取得します。
- SqlSessionFactoryのインスタンスは、データベースを操作するSqlSessionのインスタンスを取得し、このインスタンスを介してデータベースを操作できます。
コード例
- configuration.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="ssm/jdbc.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="ssm/BlogMapper.xml"/>
</mappers>
</configuration>
- xml構成デモを読む
public class GetSqlSessionFactoryFromXML {
public static void main(String[] args) throws IOException {
//配置文件的名称
String resource = "ssm/configuration.xml";
//通过Mybatis包中的Resources对象很轻松的获取到配置文件
Reader reader = Resources.getResourceAsReader(resource);
//通过SqlSessionFactoryBuilder创建
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
//获得session实例
SqlSession session =sqlSessionFactory.openSession();
User user = new User();
user.setId(8);
//完成数据库的插入
session.insert("add", user);
session.commit();
session.close();
System.out.println(sqlSessionFactory);
}
}
- javaコード構成
@Bean
public SqlSessionFactory sqlSessionFactory(){
try {
// 数据源连接信息
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("test");
dataSource.setUsername("test");
dataSource.setPassword("test");
// 采用Mybatis的JDBC事务方式
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("myenverniement", transactionFactory, dataSource);
// 创建Configuration对象
Configuration configuration = new Configuration(environment);
configuration.addMapper(MetaDataTagMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
SqlSession sqlSession = sqlSessionFactory.openSession();
logger.info("===========================SqlSessionFactory配置完成");
return sqlSessionFactory;
}catch (Exception e){
logger.error("===========================SqlSessionFactory配置失败"+e.getMessage(),e);
return null;
}
}
@Bean
public SqlSession sqlSession(SqlSessionFactory sqlSessionFactory){
try{
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Object> objects = sqlSession.selectList("select 1");
return sqlSession;
}catch (Exception e){
logger.info(e.getMessage());
return null;
}
}
SqlSession
SqlSessionの作成手順:
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);
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();
}
}
- 構成から環境を取得します。
- 環境からデータデータを取得します。
- 環境からTransactionFactoryを取得します。
- DataSourceからデータベース接続オブジェクトConnectionを取得します。
- 取得したデータベースにトランザクションオブジェクトTransactionを作成します。
- Executorオブジェクトを作成します。
- SqlSessionオブジェクトを作成します。
DefaultSqlSession返信SqlSession
// statement Mapper接口的名称
// parameter sql参数
// rowsBounds 分页参数
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
// ms对应Xml中的一个语句,如select、insert等
MappedStatement ms = configuration.getMappedStatement(statement);
// 调用Executor处理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();
}
}
エグゼキュータインターフェイス
MybatisのすべてのMapperステートメントは、Executorを介して実行されます。ExecutorはSqlSessionにバインドされており、各SqlSessionには、Configurationによって作成された新しいExecutorオブジェクトがあります。
-
SimpleExecutor:追加の操作なしで、対応するSqlに従って直接実行します。
-
BatchExecutor:バッチ更新操作。
-
ReuseExcutor:再利用可能なエグゼキュータ。再利用の対象はStatementです。エグゼキュータは同じSqlステートメントをキャッシュするため、Statementを再作成する必要がありません。