You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AnnotationConfigApplicationContext加载MyBatis映射文件报错求助

我之前也遇到过一模一样的问题!用AnnotationConfigApplicationContext启动时出现Invalid bound statement (not found)错误,本质是因为你没在Java配置里显式指定MyBatis的mapper.xml文件位置——而之前的application.yml帮你完成了这个配置。下面是具体的解决方法:

解决步骤:通过Java配置类绑定MyBatis的mapper.xml

你需要创建一个Java配置类来替代yml中的MyBatis配置,让AnnotationConfigApplicationContext能正确加载mapper.xml文件。

1. 编写MyBatis专属配置类

创建带有@Configuration注解的配置类,在里面配置数据源、SqlSessionFactory,并指定mapper.xml的路径:

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;

@Configuration
// 扫描你的Mapper接口所在包,替换成实际的包路径
@MapperScan(basePackages = {"com.hello.user.dao", "com.hello.task.dao"})
public class MyBatisConfig {

    private final DataSource dataSource;

    // 构造注入数据源(假设你已配置好DataSource,比如用HikariCP)
    public MyBatisConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        
        // 关键操作:指定mapper.xml文件位置,对应yml中的mybatis.mapperLocations
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(
            resolver.getResources("classpath:com/hello/user/dao/mapper/*.xml"),
            resolver.getResources("classpath:com/hello/task/dao/mapper/*.xml")
        );

        // 若有MyBatis全局配置文件(如mybatis-config.xml),可在此添加
        // sessionFactory.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
        
        return sessionFactory;
    }
}

2. 确保配置类被Spring扫描到

你的主类已经标注了@ComponentScan(basePackages={"com.hello"}),只要MyBatisConfig类在com.hello包或其子包下,就会被自动扫描加载。如果配置类不在这个范围内,需要在主类上添加@Import(MyBatisConfig.class)手动导入。

3. 启动验证

现在用AnnotationConfigApplicationContext启动应用时,SqlSessionFactory会正确找到所有mapper.xml文件,不会再出现绑定语句找不到的错误。

补充:如果还没配置DataSource

如果项目里没有现成的DataSource Bean,可以在配置类中添加如下示例(以HikariCP为例):

@Bean
public DataSource dataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/your_database");
    dataSource.setUsername("your_username");
    dataSource.setPassword("your_password");
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    return dataSource;
}

内容的提问来源于stack exchange,提问作者HongyanShen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:48:29