Mybatis-Spring整合Spring

  

  因为 MyBatis 用 SqlSessionFactory 来创建 SqlSession ,SqlSessionFactoryBuilder 创建 SqlSessionFactory ,而在 Mybatis-Spring 中提供了继承自 Spring 接口 FactoryBean 的 SqlSessionFactoryBean 类,它提供 getObject() 方法来获取 SqlSessionFactory 。所以可以用基于Java配置的方式配置 SqlSessionFactory 。

  MybatisDataConfig配置类配置了MyBatis的dataSource、sql语句xml配置文件路径、数据库类型包路径

 1 @Configuration
 2 public class MybatisDataConfig {
 3 
 4   private DataSource dataSource;
 5 
 6   @Autowired
 7   public MybatisDataConfig(DataSource dataSource) {
 8     this.dataSource = dataSource;
 9   }
10 
11   /**
12    * 必须指定名称 sqlSessionFactory.
13    */
14   @Bean("sqlSessionFactory")
15   public SqlSessionFactory getBean() throws Exception {
16     SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
17     factoryBean.setDataSource(dataSource);
18 
19     ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
20     factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));
21     factoryBean.setTypeAliasesPackage("com.test.entity");
22     return factoryBean.getObject();
23   }
24 
25 }

  为了减少xml配置,Mybatis-Spring还提供了 MapperScannerConfigurer 类,它可以扫描映射类,自动创建 MapperFactoryBean 来吧dao注入给service,也就是说service可以直接通过@Autowired等方式,直接注入dao层接口实例,而dao层的接口不需要其他额外的配置。

 1 /**
 2  * <p>MybatisScannerConfig 和 MybatisDataConfig 需要分开写.</p>
 3  * <p>而 MybatisScannerConfig 比 MybatisDataConfig 加载早.</p>
 4  * <p>所以要定义@AutoConfigureAfter.</p>
 5  * <p>否则 MybatisDataConfig 先加载会找不到 dataSource.</p>
 6  * @see MybatisDataConfig
 7  */
 8 @Configuration
 9 @AutoConfigureAfter(MybatisDataConfig.class)
10 public class MybatisScannerConfig {
11 
12   /**
13    * 基于Java配置sqlSessionFactory,扫描dao层.
14    * @return 配置实例
15    */
16   @Bean
17   public MapperScannerConfigurer getConfig() {
18     MapperScannerConfigurer configurer = new MapperScannerConfigurer();
19     configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
20     configurer.setBasePackage("com.test.dao");
21     return configurer;
22   }
23 }

 项目DemoMiniJavaWeb

 

posted @ 2017-12-10 14:31  O&#39;Neal  阅读(268)  评论(0编辑  收藏  举报