mybatis-spring java annotation for multiple dataso

2019-09-09 21:24发布

问题:

I can use the following code to configure multiple mybatis datasources in spring. What is the way to do it in mybatis-spring using java annotations and configuration (No xml)?

public class DataSourceSqlSessionFactory {

   private Logger logger = LoggerFactory.getLogger(getClass());

   private final static String MYBATIS_CONFIG = "mybatis-config-datasource.xml" ;

   public final static String AMDB_ENVIRONMENT_ID = "DB1" ;

   public final static String AODB_ENVIRONMENT_ID = "DB2" ;

   public SqlSessionFactory getSqlSessionFactory(String environment){
       InputStream inputStream = null ;
       SqlSessionFactory sqlSessionFactory = null ;
       try {
           inputStream = Resources.getResourceAsStream(MYBATIS_CONFIG);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream , environment);
           inputStream.close();
           logger.info("Get ["+environment +"] data source connection");
       } catch (IOException e) {
           logger.error("Get ["+environment +"] data source connection failed, error messages : " + e);
       }
       return sqlSessionFactory ;
   }

}

回答1:

You simply need to register your mappers with @MapperScan annotation. The result maps however can be added to the configuration object provided to the SqlSessionFactoryBuilder.

Write the following in your 'getSqlSessionFactory' method:

org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration(environment);
config.addResultMap(someResultMap);
return new SqlSessionFactoryBuilder().build(config);

And you are done. Enjoy!