springboot用javaConfig写Mybatis自定义配置

这篇博客主要介绍了在SpringBoot项目中如何使用Java Config替代XML配置来设置Mybatis。作者指出,虽然大部分教程仍然使用XML配置,但在大型项目中,自动配置可能无法满足需求。文中详细记录了配置过程,包括pom.xml中的依赖引入,mybatis的javaConfig配置,以及重要的MyBatis runtime settings。同时,提供了application-mybatis.yml的配置示例和相关参考资料链接。
摘要由CSDN通过智能技术生成

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值