springboot用javaConfig写Mybatis自定义配置

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

SettingDescriptionValid ValuesDefault
cacheEnabledGlobally enables or disables any caches configured in any mapper under this configuration.true | falsetrue
lazyLoadingEnabledGlobally enables or disables lazy loading. When enabled, all relations will be lazily loaded. This value can be superseded for an specific relation by using the fetchType attribute on it.true | falsefalse
aggressiveLazyLoadingWhen enabled, any method call will load all the lazy properties of the object. Otherwise, each property is loaded on demand (see also lazyLoadTriggerMethods).true | falsefalse (true in ≤3.4.1)
multipleResultSetsEnabledAllows or disallows multiple ResultSets to be returned from a single statement (compatible driver required).true | falsetrue
useColumnLabelUses the column label instead of the column name. Different drivers behave differently in this respect. Refer to the driver documentation, or test out both modes to determine how your driver behaves.true | falsetrue
useGeneratedKeysAllows JDBC support for generated keys. A compatible driver is required. This setting forces generated keys to be used if set to true, as some drivers deny compatibility but still work (e.g. Derby).true | falseFalse
autoMappingBehaviorSpecifies if and how MyBatis should automatically map columns to fields/properties. NONE disables auto-mapping. PARTIAL will only auto-map results with no nested result mappings defined inside. FULL will auto-map result mappings of any complexity (containing nested or otherwise).NONE, PARTIAL, FULLPARTIAL
autoMappingUnknownColumnBehaviorSpecify the behavior when detects an unknown column (or unknown property type) of automatic mapping target.
  • NONE: Do nothing
  • WARNING: Output warning log (The log level of 'org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' must be set to WARN)
  • FAILING: Fail mapping (Throw SqlSessionException)
NONE, WARNING, FAILINGNONE
defaultExecutorTypeConfigures the default executor. SIMPLE executor does nothing special. REUSE executor reuses prepared statements. BATCH executor reuses statements and batches updates.SIMPLE REUSE BATCHSIMPLE
defaultStatementTimeoutSets the number of seconds the driver will wait for a response from the database.Any positive integerNot Set (null)
defaultFetchSizeSets the driver a hint as to control fetching size for return results. This parameter value can be override by a query setting.Any positive integerNot Set (null)
safeRowBoundsEnabledAllows using RowBounds on nested statements. If allow, set the false.true | falseFalse
safeResultHandlerEnabledAllows using ResultHandler on nested statements. If allow, set the false.true | falseTrue
mapUnderscoreToCamelCaseEnables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn.true | falseFalse
localCacheScopeMyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession.SESSION | STATEMENTSESSION
jdbcTypeForNullSpecifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values like NULL, VARCHAR or OTHER.JdbcType enumeration. Most common are: NULL, VARCHAR and OTHEROTHER
lazyLoadTriggerMethodsSpecifies which Object's methods trigger a lazy loadA method name list separated by commasequals,clone,hashCode,toString
defaultScriptingLanguageSpecifies the language used by default for dynamic SQL generation.A type alias or fully qualified class name.org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
defaultEnumTypeHandlerSpecifies the TypeHandler used by default for Enum. (Since: 3.4.5)A type alias or fully qualified class name.org.apache.ibatis.type.EnumTypeHandler
callSettersOnNullsSpecifies if setters or map's put method will be called when a retrieved value is null. It is useful when you rely on Map.keySet() or null value initialization. Note primitives such as (int,boolean,etc.) will not be set to null.true | falsefalse
returnInstanceForEmptyRowMyBatis, by default, returns null when all the columns of a returned row are NULL. When this setting is enabled, MyBatis returns an empty instance instead. Note that it is also applied to nested results (i.e. collectioin and association). Since: 3.4.2true | falsefalse
logPrefixSpecifies the prefix string that MyBatis will add to the logger names.Any StringNot set
logImplSpecifies which logging implementation MyBatis should use. If this setting is not present logging implementation will be autodiscovered.SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGINGNot set
proxyFactorySpecifies the proxy tool that MyBatis will use for creating lazy loading capable objects.CGLIB | JAVASSISTJAVASSIST (MyBatis 3.3 or above)
vfsImplSpecifies VFS implementationsFully qualified class names of custom VFS implementation separated by commas.Not set
useActualParamNameAllow referencing statement parameters by their actual names declared in the method signature. To use this feature, your project must be compiled in Java 8 with -parameters option. (Since: 3.4.1)true | falsetrue
configurationFactorySpecifies the class that provides an instance of Configuration. The returned Configuration instance is used to load lazy properties of deserialized objects. This class must have a method with a signature static Configuration getConfiguration(). (Since: 3.2.3)

至于我的application-mybatis.yml配置文件如何弄,如下

mybatis:
  mapperLocations: classpath*:mapper*/*.xml
  default-statement-timeout: 30


关于相关资料的查找:

http://www.mybatis.org/mybatis-3/configuration.html#settings

http://www.mybatis.org/spring/apidocs/reference/org/mybatis/spring/package-summary.html

### 如何在 Spring Boot 中配置 MyBatis自定义 Mapper 路径 要在 Spring Boot 中配置 MyBatis 并指定自定义的 Mapper 文件路径,可以通过 `application.yml` 或 `application.properties` 来完成。以下是详细的说明: #### 1. 配置文件中的设置 通过配置文件可以指定 MyBatis 的 SQL 映射文件的位置以及全局配置文件的位置。例如,在 YAML 格式的配置文件中,可以这样[^1]: ```yaml spring: datasource: username: root password: 1234 url: jdbc:mysql://localhost:3306/mydb driver-class-name: com.mysql.cj.jdbc.Driver mybatis: config-location: classpath:mybatis/mybatis-config.xml # 全局配置文件位置 mapper-locations: classpath:mybatis/mapper/*.xml # 自定义 Mapper 文件路径 ``` 上述配置指定了两个重要参数: - **config-location**: 定义了 MyBatis 的全局 XML 配置文件所在位置。 - **mapper-locations**: 指定 SQL 映射文件所在的目录。 如果需要更灵活的方式加载多个路径下的 Mapper 文件,则可以在 `mapper-locations` 使用通配符或者分号分割多个路径。 --- #### 2. Java 配置类支持 除了通过配置文件外,还可以借助 Java 配置类实现更加复杂的场景需求。比如引入额外的功能模块或动态调整资源加载逻辑时,推荐创建一个专门用于 MyBatis配置类并标注相应的注解[^2]。 下面是一个简单的例子展示如何手动注册 Mapper 所需的内容: ```java package org.springboot.sample.config; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @MapperScan(basePackages = "org.springboot.sample.mapper") // 设置 Mapper 接口扫描的基础包 public class MyBatisConfig { @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { // 可在此处进一步定制化 SqlSessionFactory 实现细节... return new SqlSessionFactory(); } } ``` 此方法允许开发者显式声明哪些包内的接口会被识别为 MyBatis Mappers,并且能够方便地注入其他 Bean 进行依赖管理。 --- #### 3. 动态多数据源的支持(可选) 对于某些复杂项目可能涉及切换不同数据库实例的情况,这时就需要考虑加入动态数据源功能。通常做法是先定义好各个可用的数据源类型作为枚举值[^5],再配合 AOP 切面技术实现在运行期间无缝转换目标连接池。 示例代码如下所示: ```java // 枚举表示不同的数据源名称 public enum DBTypeEnum { MASTER, SLAVE1, SLAVE2; } // 数据源上下文持有器 @Component public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); public static void setDbType(DBTypeEnum dbType) { contextHolder.set(dbType.name()); } public static String getDbType() { return contextHolder.get(); } public static void clearDbType() { contextHolder.remove(); } } ``` 随后还需要编具体的路由策略和服务提供者来绑定这些抽象概念至实际物理对象之上。 --- #### 总结 综上所述,无论是采用静态方式还是动态机制都可以很好地满足大多数业务系统的开发诉求。只需按照官方文档指引合理安排各项属性即可轻松达成预期效果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值