GlobalConfiguration.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /**
  2. * Copyright (c) 2011-2014, hubin (jobob@qq.com).
  3. * <p>
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. * <p>
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. * <p>
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.baomidou.mybatisplus.entity;
  17. import java.sql.Connection;
  18. import java.sql.SQLException;
  19. import java.util.Map;
  20. import java.util.Set;
  21. import java.util.concurrent.ConcurrentHashMap;
  22. import java.util.concurrent.ConcurrentSkipListSet;
  23. import javax.sql.DataSource;
  24. import org.apache.ibatis.logging.Log;
  25. import org.apache.ibatis.logging.LogFactory;
  26. import org.apache.ibatis.session.Configuration;
  27. import org.apache.ibatis.session.SqlSession;
  28. import org.apache.ibatis.session.SqlSessionFactory;
  29. import com.baomidou.mybatisplus.MybatisSqlSessionTemplate;
  30. import com.baomidou.mybatisplus.enums.DBType;
  31. import com.baomidou.mybatisplus.enums.FieldStrategy;
  32. import com.baomidou.mybatisplus.enums.IdType;
  33. import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
  34. import com.baomidou.mybatisplus.incrementer.IKeyGenerator;
  35. import com.baomidou.mybatisplus.mapper.AutoSqlInjector;
  36. import com.baomidou.mybatisplus.mapper.ISqlInjector;
  37. import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
  38. import com.baomidou.mybatisplus.toolkit.IOUtils;
  39. import com.baomidou.mybatisplus.toolkit.JdbcUtils;
  40. import com.baomidou.mybatisplus.toolkit.SqlReservedWords;
  41. import com.baomidou.mybatisplus.toolkit.StringUtils;
  42. import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
  43. /**
  44. * <p>
  45. * Mybatis全局缓存
  46. * </p>
  47. *
  48. * @author Caratacus
  49. * @since 2016-12-06
  50. */
  51. public class GlobalConfiguration implements Cloneable {
  52. /**
  53. * 默认参数
  54. */
  55. public static final GlobalConfiguration DEFAULT = new GlobalConfiguration();
  56. // 日志
  57. private static final Log logger = LogFactory.getLog(GlobalConfiguration.class);
  58. /**
  59. * 缓存全局信息
  60. */
  61. private static final Map<String, GlobalConfiguration> GLOBAL_CONFIG = new ConcurrentHashMap<>();
  62. // 逻辑删除全局值
  63. private String logicDeleteValue = null;
  64. // 逻辑未删除全局值
  65. private String logicNotDeleteValue = null;
  66. // 数据库类型(默认 MySql)
  67. private DBType dbType = DBType.MYSQL;
  68. // 主键类型(默认 ID_WORKER)
  69. private IdType idType = IdType.ID_WORKER;
  70. // 表名、字段名、是否使用下划线命名(默认 false)
  71. private boolean dbColumnUnderline = false;
  72. // SQL注入器
  73. private ISqlInjector sqlInjector;
  74. // 表关键词 key 生成器
  75. private IKeyGenerator keyGenerator;
  76. // 元对象字段填充控制器
  77. private MetaObjectHandler metaObjectHandler = new DefaultMetaObjectHandler();
  78. // 字段验证策略
  79. private FieldStrategy fieldStrategy = FieldStrategy.NOT_NULL;
  80. // 是否刷新mapper
  81. private boolean isRefresh = false;
  82. // 是否自动获取DBType
  83. private boolean isAutoSetDbType = true;
  84. // 是否大写命名
  85. private boolean isCapitalMode = false;
  86. // 标识符
  87. private String identifierQuote;
  88. // 缓存当前Configuration的SqlSessionFactory
  89. private SqlSessionFactory sqlSessionFactory;
  90. // 缓存已注入CRUD的Mapper信息
  91. private Set<String> mapperRegistryCache = new ConcurrentSkipListSet<>();
  92. // 单例重用SqlSession
  93. private SqlSession sqlSession;
  94. public GlobalConfiguration() {
  95. // 构造方法
  96. }
  97. public GlobalConfiguration(ISqlInjector sqlInjector) {
  98. this.sqlInjector = sqlInjector;
  99. }
  100. /**
  101. * 获取当前的SqlSessionFactory
  102. *
  103. * @param clazz
  104. * @return
  105. */
  106. public static SqlSessionFactory currentSessionFactory(Class<?> clazz) {
  107. String configMark = TableInfoHelper.getTableInfo(clazz).getConfigMark();
  108. GlobalConfiguration mybatisGlobalConfig = GlobalConfiguration.getGlobalConfig(configMark);
  109. return mybatisGlobalConfig.getSqlSessionFactory();
  110. }
  111. /**
  112. * 获取默认MybatisGlobalConfig
  113. *
  114. * @return
  115. */
  116. public static GlobalConfiguration defaults() {
  117. try {
  118. GlobalConfiguration clone = DEFAULT.clone();
  119. clone.setSqlInjector(new AutoSqlInjector());
  120. return clone;
  121. } catch (CloneNotSupportedException e) {
  122. throw new MybatisPlusException("ERROR: CLONE MybatisGlobalConfig DEFAULT FAIL ! Cause:" + e);
  123. }
  124. }
  125. /**
  126. * <p>
  127. * 设置全局设置(以configuration地址值作为Key)
  128. * <p/>
  129. *
  130. * @param configuration
  131. * @param mybatisGlobalConfig
  132. * @return
  133. */
  134. public static void setGlobalConfig(Configuration configuration, GlobalConfiguration mybatisGlobalConfig) {
  135. if (configuration == null || mybatisGlobalConfig == null) {
  136. throw new MybatisPlusException("Error: Could not setGlobalConfig");
  137. }
  138. // 设置全局设置
  139. GLOBAL_CONFIG.put(configuration.toString(), mybatisGlobalConfig);
  140. }
  141. /**
  142. * 获取MybatisGlobalConfig (统一所有入口)
  143. *
  144. * @param configuration
  145. * @return
  146. */
  147. public static GlobalConfiguration getGlobalConfig(Configuration configuration) {
  148. if (configuration == null) {
  149. throw new MybatisPlusException("Error: You need Initialize MybatisConfiguration !");
  150. }
  151. return getGlobalConfig(configuration.toString());
  152. }
  153. /**
  154. * 获取MybatisGlobalConfig (统一所有入口)
  155. *
  156. * @param configMark
  157. * @return
  158. */
  159. public static GlobalConfiguration getGlobalConfig(String configMark) {
  160. GlobalConfiguration cache = GLOBAL_CONFIG.get(configMark);
  161. if (cache == null) {
  162. // 没有获取全局配置初始全局配置
  163. logger.debug("DeBug: MyBatis Plus Global configuration Initializing !");
  164. GLOBAL_CONFIG.put(configMark, DEFAULT);
  165. return DEFAULT;
  166. }
  167. return cache;
  168. }
  169. public static DBType getDbType(Configuration configuration) {
  170. return getGlobalConfig(configuration).getDbType();
  171. }
  172. public static IKeyGenerator getKeyGenerator(Configuration configuration) {
  173. return getGlobalConfig(configuration).getKeyGenerator();
  174. }
  175. public static IdType getIdType(Configuration configuration) {
  176. return getGlobalConfig(configuration).getIdType();
  177. }
  178. public static boolean isDbColumnUnderline(Configuration configuration) {
  179. return getGlobalConfig(configuration).isDbColumnUnderline();
  180. }
  181. public static ISqlInjector getSqlInjector(Configuration configuration) {
  182. // fix #140
  183. GlobalConfiguration globalConfiguration = getGlobalConfig(configuration);
  184. ISqlInjector sqlInjector = globalConfiguration.getSqlInjector();
  185. if (sqlInjector == null) {
  186. sqlInjector = new AutoSqlInjector();
  187. globalConfiguration.setSqlInjector(sqlInjector);
  188. }
  189. return sqlInjector;
  190. }
  191. public IKeyGenerator getKeyGenerator() {
  192. return keyGenerator;
  193. }
  194. public void setKeyGenerator(IKeyGenerator keyGenerator) {
  195. this.keyGenerator = keyGenerator;
  196. }
  197. public static MetaObjectHandler getMetaObjectHandler(Configuration configuration) {
  198. return getGlobalConfig(configuration).getMetaObjectHandler();
  199. }
  200. public static FieldStrategy getFieldStrategy(Configuration configuration) {
  201. return getGlobalConfig(configuration).getFieldStrategy();
  202. }
  203. public static boolean isRefresh(Configuration configuration) {
  204. return getGlobalConfig(configuration).isRefresh();
  205. }
  206. public static boolean isAutoSetDbType(Configuration configuration) {
  207. return getGlobalConfig(configuration).isAutoSetDbType();
  208. }
  209. public static Set<String> getMapperRegistryCache(Configuration configuration) {
  210. return getGlobalConfig(configuration).getMapperRegistryCache();
  211. }
  212. public static String getIdentifierQuote(Configuration configuration) {
  213. return getGlobalConfig(configuration).getIdentifierQuote();
  214. }
  215. public static SqlSession getSqlSession(Configuration configuration) {
  216. return getGlobalConfig(configuration).getSqlSession();
  217. }
  218. /**
  219. * 设置元数据相关属性
  220. *
  221. * @param dataSource
  222. * @param globalConfig
  223. */
  224. public static void setMetaData(DataSource dataSource, GlobalConfiguration globalConfig) {
  225. Connection connection = null;
  226. try {
  227. connection = dataSource.getConnection();
  228. String jdbcUrl = connection.getMetaData().getURL();
  229. // 设置全局关键字
  230. globalConfig.setSqlKeywords(connection.getMetaData().getSQLKeywords());
  231. // 自动设置数据库类型
  232. if (globalConfig.isAutoSetDbType()) {
  233. globalConfig.setDbTypeByJdbcUrl(jdbcUrl);
  234. }
  235. } catch (SQLException e) {
  236. logger.warn("Warn: GlobalConfiguration setMetaData Fail ! Cause:" + e);
  237. } finally {
  238. IOUtils.closeQuietly(connection);
  239. }
  240. }
  241. public String getLogicDeleteValue() {
  242. return logicDeleteValue;
  243. }
  244. public void setLogicDeleteValue(String logicDeleteValue) {
  245. this.logicDeleteValue = logicDeleteValue;
  246. }
  247. public String getLogicNotDeleteValue() {
  248. return logicNotDeleteValue;
  249. }
  250. public void setLogicNotDeleteValue(String logicNotDeleteValue) {
  251. this.logicNotDeleteValue = logicNotDeleteValue;
  252. }
  253. public DBType getDbType() {
  254. return dbType;
  255. }
  256. public void setDbType(String dbType) {
  257. this.dbType = DBType.getDBType(dbType);
  258. this.isAutoSetDbType = false;
  259. }
  260. public void setDbTypeByJdbcUrl(String jdbcUrl) {
  261. this.dbType = JdbcUtils.getDbType(jdbcUrl);
  262. }
  263. public IdType getIdType() {
  264. return idType;
  265. }
  266. public void setIdType(int idType) {
  267. this.idType = IdType.getIdType(idType);
  268. }
  269. public boolean isDbColumnUnderline() {
  270. return dbColumnUnderline;
  271. }
  272. public void setDbColumnUnderline(boolean dbColumnUnderline) {
  273. this.dbColumnUnderline = dbColumnUnderline;
  274. }
  275. public ISqlInjector getSqlInjector() {
  276. return sqlInjector;
  277. }
  278. public void setSqlInjector(ISqlInjector sqlInjector) {
  279. this.sqlInjector = sqlInjector;
  280. }
  281. public MetaObjectHandler getMetaObjectHandler() {
  282. return metaObjectHandler;
  283. }
  284. public void setMetaObjectHandler(MetaObjectHandler metaObjectHandler) {
  285. this.metaObjectHandler = metaObjectHandler;
  286. }
  287. public FieldStrategy getFieldStrategy() {
  288. return fieldStrategy;
  289. }
  290. public void setFieldStrategy(int fieldStrategy) {
  291. this.fieldStrategy = FieldStrategy.getFieldStrategy(fieldStrategy);
  292. }
  293. public boolean isRefresh() {
  294. return isRefresh;
  295. }
  296. public void setRefresh(boolean refresh) {
  297. this.isRefresh = refresh;
  298. }
  299. public boolean isAutoSetDbType() {
  300. return isAutoSetDbType;
  301. }
  302. public void setAutoSetDbType(boolean autoSetDbType) {
  303. this.isAutoSetDbType = autoSetDbType;
  304. }
  305. public Set<String> getMapperRegistryCache() {
  306. return mapperRegistryCache;
  307. }
  308. public void setMapperRegistryCache(Set<String> mapperRegistryCache) {
  309. this.mapperRegistryCache = mapperRegistryCache;
  310. }
  311. public SqlSessionFactory getSqlSessionFactory() {
  312. return sqlSessionFactory;
  313. }
  314. public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
  315. this.sqlSessionFactory = sqlSessionFactory;
  316. this.sqlSession = new MybatisSqlSessionTemplate(sqlSessionFactory);
  317. }
  318. public boolean isCapitalMode() {
  319. return isCapitalMode;
  320. }
  321. public void setCapitalMode(boolean isCapitalMode) {
  322. this.isCapitalMode = isCapitalMode;
  323. }
  324. public String getIdentifierQuote() {
  325. if (null == identifierQuote) {
  326. return dbType.getQuote();
  327. }
  328. return identifierQuote;
  329. }
  330. public void setIdentifierQuote(String identifierQuote) {
  331. this.identifierQuote = identifierQuote;
  332. }
  333. public void setSqlKeywords(String sqlKeywords) {
  334. if (StringUtils.isNotEmpty(sqlKeywords)) {
  335. SqlReservedWords.RESERVED_WORDS.addAll(StringUtils.splitWorker(sqlKeywords.toUpperCase(), ",", -1, false));
  336. }
  337. }
  338. public SqlSession getSqlSession() {
  339. return sqlSession;
  340. }
  341. @Override
  342. protected GlobalConfiguration clone() throws CloneNotSupportedException {
  343. return (GlobalConfiguration) super.clone();
  344. }
  345. /**
  346. * <p>
  347. * 标记全局设置 (统一所有入口)
  348. * </p>
  349. *
  350. * @param sqlSessionFactory
  351. * @return
  352. */
  353. public SqlSessionFactory signGlobalConfig(SqlSessionFactory sqlSessionFactory) {
  354. if (null != sqlSessionFactory) {
  355. setGlobalConfig(sqlSessionFactory.getConfiguration(), this);
  356. }
  357. return sqlSessionFactory;
  358. }
  359. }