How can I avoid Mybatis reloading configuration for every `SqlSessionTemplate`?

82 Views Asked by At

Recently I noticed that my project takes quite a long time initializing Mybatis-related beans and classes. My database has tens of shards and there is a wrapper that routes queries to the shards. After some research, I found out that inside the wrapper each shard holds a separate SqlSessionTemplate, and every time it is created and initialized, it loads Mybatis configuration and mappers. Each load takes less than a second but it sums to several tens of seconds.

Since all session templates are exactly the same except for their data sources, I don't want the load happens every time the session template is initialized. So I registered the Mybatis configuration as a bean and injected it into each SqlSessionFactoryBean as follows:

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setConfiguration(configuration);

But all the sql sessions ended up sharing the same data source, since the data source was being stored in the Configuration, whose singleton bean was shared across all the SqlSessionFactoryBeans.

I searched for a way to clone the Configuration object without reloading all the configs, but couldn't find any.

If you have any idea how to instantiate several SqlSessionTemplates without reloading the Mybatis configs and mappers every time, whether it reuses Configuration or SqlSessionFactoryBean, please let me know.

Versions: Spring 4.3, Mybatis 3.4, Mybatis-spring 1.3

0

There are 0 best solutions below