MybatisPlusProperties.java 16 KB

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