Spring踩坑:整合mybatis-Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: url

1.首先检查mapper接口和xml文件映射,没问题。如果是映射问题,会报Invalid bound statement (not found)

2.几经排查,发现是加载配置的问题。

import org.springframework.context.annotation.*;

@Configuration
@ComponentScan("com.ryy")
@EnableAspectJAutoProxy
@PropertySource("classpath:jdbc.properties")
@Import({JDBCConfig.class})
public class SpringConfig {
}

这里,我把JDBC连接池(DataSource)和mybatis的配置放到了一个配置类里,这就是报错原因。

public class JDBCConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setPassword(password);
        druidDataSource.setUsername(username);
        return druidDataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.ryy.pojo");
        return sqlSessionFactoryBean;
    }
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.ryy.mappers");
        return mapperScannerConfigurer;
    }
}

拆开,SqlSessionFactoryBean和MapperScannerConfigurer单独配置到MybatisConfig中去就没问题了。MybatisConfig的初始化会使spring无法加载配置文件中的常量。

@Configuration
@EnableAspectJAutoProxy
@PropertySource("classpath:jdbc.properties")
@Import({jdbcConfig.class,myBatisConfig.class})
public class SpringConfig {
}

你可能感兴趣的:(Java,mybatis,java,spring)