springboot主张用java config代替xml配置,但在大部分博文中依然用的是xml配置讲解,很少讲解javaConfig的内容,我这里记录下自己用java config配置mybatis。
pom.xml就不多说了,日常引入
mybatis-spring-boot-starter
这个当然也可以自动加载mybatis的配置,但是在一般大项目中,自动的那些默认配置就很难满足了。
mybatis javaConfig如下:
@Configuration
@ConfigurationProperties(prefix = "mybatis")
@PropertySource("application-mybatis.yml")
public class MyBatisConfig {
private static final Logger logger = Logger.getLogger(MyBatisConfig.class);
// @Autowired
// private Environment env;
@Autowired
private DataSource druidDataSource;
@Value("${mapperLocations}")
private String mapperLocations;
@Value("${default-statement-timeout}")
private int dst;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
logger.info("sqlSessionFactory:--->mybatis.mapperLocation:" + mapperLocations );
sqlSessionFactoryBean.setDataSource(druidDataSource);
org.apache.ibatis.session.Configuration cfg = new org.apache.ibatis.session.Configuration();//configuration
cfg.setDefaultStatementTimeout(dst);//设置相关参数,我这里就只用了一个
logger.info("sqlSessionFactoryBean:-->" + sqlSessionFactoryBean.getObject());
logger.info("default-statement-timeout:" + dst);
sqlSessionFactoryBean.setConfiguration(cfg);
return sqlSessionFactoryBean.getObject();
}
相关configuration参数如下:
settings
These are extremely important tweaks that modify the way that MyBatis behaves at runtime. The following table describes the settings, their meanings and their default values.
Setting | Description | Valid Values | Default |
---|---|---|---|
cacheEnabled | Globally enables or disables any caches configured in any mapper under this configuration. | true | false | tru |