MybatisPlusProperties.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * Copyright (c) 2011-2023, baomidou (jobob@qq.com).
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.baomidou.mybatisplus.autoconfigure;
  17. import com.baomidou.mybatisplus.core.config.GlobalConfig;
  18. import com.baomidou.mybatisplus.core.toolkit.Constants;
  19. import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
  20. import lombok.Data;
  21. import lombok.Getter;
  22. import lombok.Setter;
  23. import lombok.experimental.Accessors;
  24. import org.apache.ibatis.io.VFS;
  25. import org.apache.ibatis.logging.Log;
  26. import org.apache.ibatis.mapping.ResultSetType;
  27. import org.apache.ibatis.scripting.LanguageDriver;
  28. import org.apache.ibatis.session.AutoMappingBehavior;
  29. import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
  30. import org.apache.ibatis.session.Configuration;
  31. import org.apache.ibatis.session.ExecutorType;
  32. import org.apache.ibatis.session.LocalCacheScope;
  33. import org.apache.ibatis.type.JdbcType;
  34. import org.apache.ibatis.type.TypeHandler;
  35. import org.springframework.boot.context.properties.ConfigurationProperties;
  36. import org.springframework.boot.context.properties.NestedConfigurationProperty;
  37. import org.springframework.boot.context.properties.PropertyMapper;
  38. import org.springframework.core.io.Resource;
  39. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  40. import org.springframework.core.io.support.ResourcePatternResolver;
  41. import java.io.IOException;
  42. import java.util.Optional;
  43. import java.util.Properties;
  44. import java.util.Set;
  45. import java.util.stream.Stream;
  46. /**
  47. * Configuration properties for MyBatis.
  48. *
  49. * @author Eddú Meléndez
  50. * @author Kazuki Shimizu
  51. */
  52. @Data
  53. @Accessors(chain = true)
  54. @ConfigurationProperties(prefix = Constants.MYBATIS_PLUS)
  55. public class MybatisPlusProperties {
  56. private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
  57. /**
  58. * Location of MyBatis xml config file.
  59. */
  60. private String configLocation;
  61. /**
  62. * Locations of MyBatis mapper files.
  63. *
  64. * @since 3.1.2 add default value
  65. */
  66. private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};
  67. /**
  68. * Packages to search type aliases. (Package delimiters are ",; \t\n")
  69. */
  70. private String typeAliasesPackage;
  71. /**
  72. * The super class for filtering type alias.
  73. * If this not specifies, the MyBatis deal as type alias all classes that searched from typeAliasesPackage.
  74. */
  75. private Class<?> typeAliasesSuperType;
  76. /**
  77. * Packages to search for type handlers. (Package delimiters are ",; \t\n")
  78. */
  79. private String typeHandlersPackage;
  80. /**
  81. * Indicates whether perform presence check of the MyBatis xml config file.
  82. */
  83. private boolean checkConfigLocation = false;
  84. /**
  85. * Execution mode for {@link org.mybatis.spring.SqlSessionTemplate}.
  86. */
  87. private ExecutorType executorType;
  88. /**
  89. * The default scripting language driver class. (Available when use together with mybatis-spring 2.0.2+)
  90. * <p>
  91. * 如果设置了这个,你会至少失去几乎所有 mp 提供的功能
  92. */
  93. private Class<? extends LanguageDriver> defaultScriptingLanguageDriver;
  94. /**
  95. * Externalized properties for MyBatis configuration.
  96. */
  97. private Properties configurationProperties;
  98. /**
  99. * A Configuration object for customize default settings. If {@link #configLocation}
  100. * is specified, this property is not used.
  101. */
  102. private CoreConfiguration configuration;
  103. /**
  104. * 不再需要这个配置,放心删除
  105. *
  106. * @deprecated 2022-03-07
  107. */
  108. @Deprecated
  109. private String typeEnumsPackage;
  110. /**
  111. * TODO 全局配置
  112. */
  113. @NestedConfigurationProperty
  114. private GlobalConfig globalConfig = GlobalConfigUtils.defaults();
  115. public Resource[] resolveMapperLocations() {
  116. return Stream.of(Optional.ofNullable(this.mapperLocations).orElse(new String[0]))
  117. .flatMap(location -> Stream.of(getResources(location))).toArray(Resource[]::new);
  118. }
  119. private Resource[] getResources(String location) {
  120. try {
  121. return resourceResolver.getResources(location);
  122. } catch (IOException e) {
  123. return new Resource[0];
  124. }
  125. }
  126. /**
  127. * The configuration properties for mybatis core module.
  128. * 虽然为高版本新增开始,但为了美化配置提示,这里也在SpringBoot2上使用.
  129. *
  130. * @since 3.0.0
  131. */
  132. @Getter
  133. @Setter
  134. public static class CoreConfiguration {
  135. /**
  136. * Allows using RowBounds on nested statements. If allowed, set the false. Default is false.
  137. */
  138. private Boolean safeRowBoundsEnabled;
  139. /**
  140. * Allows using ResultHandler on nested statements. If allowed, set the false. Default is true.
  141. */
  142. private Boolean safeResultHandlerEnabled;
  143. /**
  144. * Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names
  145. * aColumn. Default is false.
  146. */
  147. private Boolean mapUnderscoreToCamelCase;
  148. /**
  149. * When enabled, any method call will load all the lazy properties of the object. Otherwise, each property is loaded
  150. * on demand (see also lazyLoadTriggerMethods). Default is false.
  151. */
  152. private Boolean aggressiveLazyLoading;
  153. /**
  154. * Allows or disallows multiple ResultSets to be returned from a single statement (compatible driver required).
  155. * Default is true.
  156. */
  157. private Boolean multipleResultSetsEnabled;
  158. /**
  159. * Allows JDBC support for generated keys. A compatible driver is required. This setting forces generated keys to be
  160. * used if set to true, as some drivers deny compatibility but still work (e.g. Derby). Default is false.
  161. */
  162. private Boolean useGeneratedKeys;
  163. /**
  164. * Uses the column label instead of the column name. Different drivers behave differently in this respect. Refer to
  165. * the driver documentation, or test out both modes to determine how your driver behaves. Default is true.
  166. */
  167. private Boolean useColumnLabel;
  168. /**
  169. * Globally enables or disables any caches configured in any mapper under this configuration. Default is true.
  170. */
  171. private Boolean cacheEnabled;
  172. /**
  173. * Specifies if setters or map's put method will be called when a retrieved value is null. It is useful when you
  174. * rely on Map.keySet() or null value initialization. Note primitives such as (int,boolean,etc.) will not be set to
  175. * null. Default is false.
  176. */
  177. private Boolean callSettersOnNulls;
  178. /**
  179. * Allow referencing statement parameters by their actual names declared in the method signature. To use this
  180. * feature, your project must be compiled in Java 8 with -parameters option. Default is true.
  181. */
  182. private Boolean useActualParamName;
  183. /**
  184. * MyBatis, by default, returns null when all the columns of a returned row are NULL. When this setting is enabled,
  185. * MyBatis returns an empty instance instead. Note that it is also applied to nested results (i.e. collection and
  186. * association). Default is false.
  187. */
  188. private Boolean returnInstanceForEmptyRow;
  189. /**
  190. * Removes extra whitespace characters from the SQL. Note that this also affects literal strings in SQL. Default is
  191. * false.
  192. */
  193. private Boolean shrinkWhitespacesInSql;
  194. /**
  195. * Specifies the default value of 'nullable' attribute on 'foreach' tag. Default is false.
  196. */
  197. private Boolean nullableOnForEach;
  198. /**
  199. * When applying constructor auto-mapping, argument name is used to search the column to map instead of relying on
  200. * the column order. Default is false.
  201. */
  202. private Boolean argNameBasedConstructorAutoMapping;
  203. /**
  204. * Globally enables or disables lazy loading. When enabled, all relations will be lazily loaded. This value can be
  205. * superseded for a specific relation by using the fetchType attribute on it. Default is False.
  206. */
  207. private Boolean lazyLoadingEnabled;
  208. /**
  209. * Sets the number of seconds the driver will wait for a response from the database.
  210. */
  211. private Integer defaultStatementTimeout;
  212. /**
  213. * Sets the driver a hint as to control fetching size for return results. This parameter value can be overridden by a
  214. * query setting.
  215. */
  216. private Integer defaultFetchSize;
  217. /**
  218. * MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default,
  219. * (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT local session will be
  220. * used just for statement execution, no data will be shared between two different calls to the same SqlSession.
  221. * Default is SESSION.
  222. */
  223. private LocalCacheScope localCacheScope;
  224. /**
  225. * Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers
  226. * require specifying the column JDBC type but others work with generic values like NULL, VARCHAR or OTHER. Default
  227. * is OTHER.
  228. */
  229. private JdbcType jdbcTypeForNull;
  230. /**
  231. * Specifies a scroll strategy when omit it per statement settings.
  232. */
  233. private ResultSetType defaultResultSetType;
  234. /**
  235. * Configures the default executor. SIMPLE executor does nothing special. REUSE executor reuses prepared statements.
  236. * BATCH executor reuses statements and batches updates. Default is SIMPLE.
  237. */
  238. private ExecutorType defaultExecutorType;
  239. /**
  240. * Specifies if and how MyBatis should automatically map columns to fields/properties. NONE disables auto-mapping.
  241. * PARTIAL will only auto-map results with no nested result mappings defined inside. FULL will auto-map result
  242. * mappings of any complexity (containing nested or otherwise). Default is PARTIAL.
  243. */
  244. private AutoMappingBehavior autoMappingBehavior;
  245. /**
  246. * Specify the behavior when detects an unknown column (or unknown property type) of automatic mapping target.
  247. * Default is NONE.
  248. */
  249. private AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior;
  250. /**
  251. * Specifies the prefix string that MyBatis will add to the logger names.
  252. */
  253. private String logPrefix;
  254. /**
  255. * Specifies which Object's methods trigger a lazy load. Default is [equals,clone,hashCode,toString].
  256. */
  257. private Set<String> lazyLoadTriggerMethods;
  258. /**
  259. * Specifies which logging implementation MyBatis should use. If this setting is not present logging implementation
  260. * will be discovered.
  261. */
  262. private Class<? extends Log> logImpl;
  263. /**
  264. * Specifies VFS implementations.
  265. */
  266. private Class<? extends VFS> vfsImpl;
  267. /**
  268. * Specifies a sql provider class that holds provider method. This class apply to the type(or value) attribute on
  269. * sql provider annotation(e.g. @SelectProvider), when these attribute was omitted.
  270. */
  271. private Class<?> defaultSqlProviderType;
  272. /**
  273. * Specifies the TypeHandler used by default for Enum.
  274. */
  275. Class<? extends TypeHandler> defaultEnumTypeHandler;
  276. /**
  277. * Specifies the class that provides an instance of Configuration. The returned Configuration instance is used to
  278. * load lazy properties of deserialized objects. This class must have a method with a signature static Configuration
  279. * getConfiguration().
  280. */
  281. private Class<?> configurationFactory;
  282. /**
  283. * Specify any configuration variables.
  284. */
  285. private Properties variables;
  286. // 新增兼容开始... mybatis 3.x 的有做属性删减 部分属性在2.x可用 3.x 已经被剔除了.
  287. /**
  288. * Specifies the language used by default for dynamic SQL generation.
  289. */
  290. private Class<? extends LanguageDriver> defaultScriptingLanguageDriver;
  291. private String databaseId;
  292. private Boolean useGeneratedShortKey;
  293. public void applyTo(Configuration target) {
  294. PropertyMapper mapper = PropertyMapper.get().alwaysApplyingWhenNonNull();
  295. mapper.from(getSafeRowBoundsEnabled()).to(target::setSafeRowBoundsEnabled);
  296. mapper.from(getSafeResultHandlerEnabled()).to(target::setSafeResultHandlerEnabled);
  297. mapper.from(getMapUnderscoreToCamelCase()).to(target::setMapUnderscoreToCamelCase);
  298. mapper.from(getAggressiveLazyLoading()).to(target::setAggressiveLazyLoading);
  299. mapper.from(getMultipleResultSetsEnabled()).to(target::setMultipleResultSetsEnabled);
  300. mapper.from(getUseGeneratedKeys()).to(target::setUseGeneratedKeys);
  301. mapper.from(getUseColumnLabel()).to(target::setUseColumnLabel);
  302. mapper.from(getCacheEnabled()).to(target::setCacheEnabled);
  303. mapper.from(getCallSettersOnNulls()).to(target::setCallSettersOnNulls);
  304. mapper.from(getUseActualParamName()).to(target::setUseActualParamName);
  305. mapper.from(getReturnInstanceForEmptyRow()).to(target::setReturnInstanceForEmptyRow);
  306. mapper.from(getShrinkWhitespacesInSql()).to(target::setShrinkWhitespacesInSql);
  307. mapper.from(getNullableOnForEach()).to(target::setNullableOnForEach);
  308. mapper.from(getArgNameBasedConstructorAutoMapping()).to(target::setArgNameBasedConstructorAutoMapping);
  309. mapper.from(getLazyLoadingEnabled()).to(target::setLazyLoadingEnabled);
  310. mapper.from(getLogPrefix()).to(target::setLogPrefix);
  311. mapper.from(getLazyLoadTriggerMethods()).to(target::setLazyLoadTriggerMethods);
  312. mapper.from(getDefaultStatementTimeout()).to(target::setDefaultStatementTimeout);
  313. mapper.from(getDefaultFetchSize()).to(target::setDefaultFetchSize);
  314. mapper.from(getLocalCacheScope()).to(target::setLocalCacheScope);
  315. mapper.from(getJdbcTypeForNull()).to(target::setJdbcTypeForNull);
  316. mapper.from(getDefaultResultSetType()).to(target::setDefaultResultSetType);
  317. mapper.from(getDefaultExecutorType()).to(target::setDefaultExecutorType);
  318. mapper.from(getAutoMappingBehavior()).to(target::setAutoMappingBehavior);
  319. mapper.from(getAutoMappingUnknownColumnBehavior()).to(target::setAutoMappingUnknownColumnBehavior);
  320. mapper.from(getVariables()).to(target::setVariables);
  321. mapper.from(getLogImpl()).to(target::setLogImpl);
  322. mapper.from(getVfsImpl()).to(target::setVfsImpl);
  323. mapper.from(getDefaultSqlProviderType()).to(target::setDefaultSqlProviderType);
  324. mapper.from(getConfigurationFactory()).to(target::setConfigurationFactory);
  325. mapper.from(getDefaultEnumTypeHandler()).to(target::setDefaultEnumTypeHandler);
  326. mapper.from(getDefaultScriptingLanguageDriver()).to(target::setDefaultScriptingLanguage);
  327. mapper.from(getDatabaseId()).to(target::setDatabaseId);
  328. mapper.from(getUseGeneratedShortKey()).to(target::setUseGeneratedKeys);
  329. }
  330. }
  331. }