helloworlde / SpringBoot-DynamicDataSource

Dynamic datasource, multiple datasource of spring boot/ distribution transaction; spring boot 多数据源,动态数据源,分布式事务
Apache License 2.0
698 stars 314 forks source link

SqlSessionFactoryBean异常报错 #5

Closed ichampionT closed 6 years ago

ichampionT commented 6 years ago

你好,我写SqlSessionFactoryBean这个方法的时候一直说mapper.xml解析错误,不存在,无法创建Bean。 @Bean @ConfigurationProperties(prefix = "mybatis") public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 配置数据源,此处配置为关键配置,如果没有将 dynamicDataSource 作为数据源则不能实现切换 sqlSessionFactoryBean.setDataSource(dynamicDataSource()); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml")); return sqlSessionFactoryBean; }

但是写成如下方法又能切换数据源了,请问一下会是什么问题? @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dynamicDataSource()); //此处设置为了解决找不到mapper文件的问题 sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml")); return sqlSessionFactoryBean.getObject(); }

@Bean
public SqlSessionTemplate sqlSessionTemplate() throws Exception {
    return new SqlSessionTemplate(sqlSessionFactory());
}
helloworlde commented 6 years ago

代码ISSUEREAMDE里面都有写,如果非要设置MapperLocation,就把@ConfigurationProperties(prefix = "mybatis") 删掉,同时设置MapperLocation

/**
 * 配置 SqlSessionFactoryBean
 * @ConfigurationProperties 在这里是为了将 MyBatis 的 mapper 位置和持久层接口的别名设置到 
 * Bean 的属性中,如果没有使用 *.xml 则可以不用该配置,否则将会产生 invalid bond statement 异常
 * 
 * @return the sql session factory bean
 */
@Bean
@ConfigurationProperties(prefix = "mybatis")
public SqlSessionFactoryBean sqlSessionFactoryBean() {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    // 配置数据源,此处配置为关键配置,如果没有将 dynamicDataSource 作为数据源则不能实现切换
    sqlSessionFactoryBean.setDataSource(dynamicDataSource());
    return sqlSessionFactoryBean;
}
# MyBatis config
mybatis.type-aliases-package=cn.com.hellowood.dynamicdatasource.mapper
mybatis.mapper-locations=mappers/**Mapper.xml