Search code examples
javamybatisspring-mybatis

mybatis @MapperScan not working


I'm trying to set up the Java config for MyBatis & the @MapperScan does not appear to be accomplishing anything. Note, I can get the application to work with XML config.

What am I missing? The com.test.mapper package definitely exists & has a file/iterface called TestMapper. The corresponding xml is in the correct location in the resources folder.

*************************** APPLICATION FAILED TO START


Description:

Field templateMapper in com.test.TestController required a bean of type 'com.test.mapper.TestMapper' that could not be found.

Action:

Consider defining a bean of type 'com.test.mapper.TestMapper' in your configuration.

Autowired that is failing

@Autowired
TestMapper _testMapper;

config

@Configuration
@MapperScan("com.test.mapper")
public class AppConfig {

   @Bean
   public DataSource dataSource() {

     SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
     try {
       dataSource.setDriverClass(com.microsoft.sqlserver.jdbc.SQLServerDriver.class);
       //dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       dataSource.setUrl("jdbc:sqlserver://server;databaseName=db1;integratedSecurity=true;");

     } catch (Exception e) {

     }
     return dataSource;
   }

   @Bean
   public DataSourceTransactionManager transactionManager() {
     return new DataSourceTransactionManager(dataSource());
   }

   @Bean
   public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
     SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

     sqlSessionFactoryBean.setTypeAliasesPackage("com.test.domain");

     sqlSessionFactoryBean.setDataSource(dataSource());
     return sqlSessionFactoryBean;
   }
}

Solution

  • I solved this. My issue wasn't with Mybatis. It was with Spring. This link to the Spring docs says to "...locate your main application class in a root package above other classes".

    I had not done that. Once I moved application class ( annotated with SpringBootApplication) then the @MapperScan annotation worked.