springboot用javaConfig寫Mybatis自定義配置

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章