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创建步骤
- 定义一个Configuration对象、其中包含数据源、事务、mapper文件资源等。
- 通过配置对象创建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配置demo
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 代码配置
不用xml 配置的时候,Mapper层中需要用注解的方式执行Sql
例如:
@Select("select * from testone")
List<Map> selecttest();
@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("com.li.test.selecttest");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();}
}
- 从配置中获取Environment;
- 从Environment中取得DataSource;
- 从Enviroment中取得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处理Sqlreturn 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();}
}
Executor接口
Mybatis中所有的Mapper语句的执行都是通过Executor进行的。Executor是跟SqlSession绑定在一起的,每一个SqlSession都拥有一个新的Executor对象,由Configuration创建。
-
SimpleExecutor:根据对应的Sql直接执行,不会做额外的操作。
-
BatchExecutor:批量更新操作。
-
ReuseExcutor:可重用的执行器,重用的对象是Statement,该执行器会缓存同一个Sql的Statement,省去Statement的重新创建。