mybatis spring 集成demo

mybatis spring 集成demo

1.环境

  • jdk8
  • mybatis3.5.2
  • Spring 5.1.9.RELEASE
  • spring-jdbc 5.1.9.RELEASE

2.引入mybatis和spring包

  
    org.mybatis
    mybatis-spring
    2.0.2
  
  
    org.mybatis
    mybatis
    3.5.2
  
  ……………………
  
    org.springframework
    spring-context
    ${spring.version}
  
  
    org.springframework
    spring-jdbc
    ${spring.version}
  

3.测试代码

public class MbatisSpringTest
{
    public static void main( String[] args )
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");
        BlogMapper blogMapper = ctx.getBean(BlogMapper.class);
        blogMapper.selectBlog(1);
    }
}

4.spring xml配置文件

下面xml配置只是为了解读mybatis spring 源码,生产环境不会用下面配置


    
    

        

        

        

        
    

    
    
        
        


        
        
    

    
    
        
        
    

SqlSessionFactoryBean:创建SqlSessionFactory,配置SqlSessionFactoryBean需要DataSource,

DataSource可以使用任何数据源。

MapperFactoryBean:需要配置SqlSessionFactory 和接口,上面配置是访问数据库dao层,创建SqlSessionTemplate 来管理SqlSession

SqlSessionTemplate : 通过sqlSessionFactory获取SqlSession 生成sqlSessionProxy, 上面例子blogMapper.selectBlog(1)中,真正执行sqlSessionProxy 调用org.mybatis.spring.SqlSessionTemplate.SqlSessionInterceptor 方法,调用org.apache.ibatis.session.defaults.DefaultSqlSession中方法

  PersistenceExceptionTranslator exceptionTranslator) {

    notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
    notNull(executorType, "Property 'executorType' is required");

    this.sqlSessionFactory = sqlSessionFactory;
    this.executorType = executorType;
    this.exceptionTranslator = exceptionTranslator;
    this.sqlSessionProxy = (SqlSession) newProxyInstance(SqlSessionFactory.class.getClassLoader(),
        new Class[] { SqlSession.class }, new SqlSessionInterceptor());
  }

5.SqlSessionFactoryBeanMapperFactoryBean初始化和执行流程图

5.1.MapperFactoryBean初始化

mybatis spring 集成demo_第1张图片
mapperFactoryBean初始化.jpg

5.2.SqlSessionFactoryBean初始化

mybatis spring 集成demo_第2张图片
mapperFactoryBean初始化.jpg

5.3.mapper执行流程

mybatis spring 集成demo_第3张图片
mybatis-spring执行流程图.jpg

参考链接

源码地址

你可能感兴趣的:(mybatis spring 集成demo)