0

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 Answer 1

0

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.