在springboot中 mybats注解sql生效,XML不生效的原因

一般在项目中都会使用springboot,如果需要使用mysql,一般都会使用阿里的druid数据库连接池,那使用这个连接池的时候,一般都会对druid做一些配置,有的人喜欢在yml中直接配置了,但是有些人可能在程序中搞一个配置类:里面的代码类似于这样:

@Configuration
@MapperScan(basePackages = "com.gbgg.graph.goods.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
public class DuridConfig {
    @Value("${spring.datasource.primary.url:#{null}}")
    private String dbUrl;
    @Value("${spring.datasource.primary.username: #{null}}")
    private String username;
    @Value("${spring.datasource.primary.password:#{null}}")
    private String password;
    @Value("${spring.datasource.primary.driverClassName:#{null}}")
    private String driverClassName;
    @Value("${spring.datasource.initialSize:#{null}}")
    private Integer initialSize;
    @Value("${spring.datasource.minIdle:#{null}}")
    private Integer minIdle;
    @Value("${spring.datasource.maxActive:#{null}}")
    private Integer maxActive;
    @Value("${spring.datasource.maxWait:#{null}}")
    private Integer maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis:#{null}}")
    private Integer timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis:#{null}}")
    private Integer minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validationQuery:#{null}}")
    private String validationQuery;
@Bean(name = "jdbcTemplate")@Primary
public JdbcTemplate jdbcTemplate() {
   return new JdbcTemplate(dataSource());
}

但是这样就会有个问题这个配置类中自己new了一个SqlSessionFactoryBean,这就会导致在yml文件中配置的xml路径根本不起作用,也就是说根本找不到xml文件,所以上面的异常就会一直报。那怎么解决呢?

就是在在即new 的这个SqlSessionFactoryBean中,把xml路径给指定了就可以了,那怎么指定呢,看下面代码:

@Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCallSettersOnNulls(true);
        bean.setConfiguration(configuration);
        bean.setVfs(SpringBootVFS.class);
        //下面这两个就是指定xml路径的
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
                bean.setDataSource(dataSource);
        return bean.getObject();
    }

这样的话就可以扫描到resource下面的xml文件了,这样的话就可以在在使用注解的情况下也使用xml进行dao层的数据书写了。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值