SqlHelper.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. * Copyright (c) 2011-2021, 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.extension.toolkit;
  17. import com.baomidou.mybatisplus.core.enums.SqlMethod;
  18. import com.baomidou.mybatisplus.core.metadata.TableInfo;
  19. import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
  20. import com.baomidou.mybatisplus.core.toolkit.*;
  21. import org.apache.ibatis.logging.Log;
  22. import org.apache.ibatis.reflection.ExceptionUtil;
  23. import org.apache.ibatis.session.ExecutorType;
  24. import org.apache.ibatis.session.SqlSession;
  25. import org.apache.ibatis.session.SqlSessionFactory;
  26. import org.mybatis.spring.MyBatisExceptionTranslator;
  27. import org.mybatis.spring.SqlSessionHolder;
  28. import org.mybatis.spring.SqlSessionUtils;
  29. import org.springframework.transaction.support.TransactionSynchronizationManager;
  30. import java.util.Collection;
  31. import java.util.List;
  32. import java.util.Objects;
  33. import java.util.function.BiConsumer;
  34. import java.util.function.BiPredicate;
  35. import java.util.function.Consumer;
  36. import java.util.function.Supplier;
  37. /**
  38. * SQL 辅助类
  39. *
  40. * @author hubin
  41. * @since 2016-11-06
  42. */
  43. public final class SqlHelper {
  44. /**
  45. * 主要用于 service 和 ar
  46. */
  47. public static SqlSessionFactory FACTORY;
  48. /**
  49. * 批量操作 SqlSession
  50. *
  51. * @param clazz 实体类
  52. * @return SqlSession
  53. */
  54. public static SqlSession sqlSessionBatch(Class<?> clazz) {
  55. // TODO 暂时让能用先,但日志会显示Closing non transactional SqlSession,因为这个并没有绑定.
  56. return sqlSessionFactory(clazz).openSession(ExecutorType.BATCH);
  57. }
  58. /**
  59. * 获取SqlSessionFactory
  60. *
  61. * @param clazz 实体类
  62. * @return SqlSessionFactory
  63. * @since 3.3.0
  64. */
  65. public static SqlSessionFactory sqlSessionFactory(Class<?> clazz) {
  66. return GlobalConfigUtils.currentSessionFactory(clazz);
  67. }
  68. /**
  69. * 获取Session
  70. *
  71. * @param clazz 实体类
  72. * @return SqlSession
  73. */
  74. public static SqlSession sqlSession(Class<?> clazz) {
  75. return SqlSessionUtils.getSqlSession(GlobalConfigUtils.currentSessionFactory(clazz));
  76. }
  77. /**
  78. * 获取TableInfo
  79. *
  80. * @param clazz 对象类
  81. * @return TableInfo 对象表信息
  82. */
  83. public static TableInfo table(Class<?> clazz) {
  84. TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
  85. Assert.notNull(tableInfo, "Error: Cannot execute table Method, ClassGenricType not found .");
  86. return tableInfo;
  87. }
  88. /**
  89. * 判断数据库操作是否成功
  90. *
  91. * @param result 数据库操作返回影响条数
  92. * @return boolean
  93. */
  94. public static boolean retBool(Integer result) {
  95. return null != result && result >= 1;
  96. }
  97. /**
  98. * 返回SelectCount执行结果
  99. *
  100. * @param result ignore
  101. * @return int
  102. */
  103. public static int retCount(Integer result) {
  104. return (null == result) ? 0 : result;
  105. }
  106. /**
  107. * 从list中取第一条数据返回对应List中泛型的单个结果
  108. *
  109. * @param list ignore
  110. * @param <E> ignore
  111. * @return ignore
  112. */
  113. public static <E> E getObject(Log log, List<E> list) {
  114. return getObject(() -> log, list);
  115. }
  116. /**
  117. * @since 3.4.3
  118. */
  119. public static <E> E getObject(Supplier<Log> supplier, List<E> list) {
  120. if (CollectionUtils.isNotEmpty(list)) {
  121. int size = list.size();
  122. if (size > 1) {
  123. Log log = supplier.get();
  124. log.warn(String.format("Warn: execute Method There are %s results.", size));
  125. }
  126. return list.get(0);
  127. }
  128. return null;
  129. }
  130. /**
  131. * 执行批量操作
  132. *
  133. * @param entityClass 实体
  134. * @param log 日志对象
  135. * @param consumer consumer
  136. * @return 操作结果
  137. * @since 3.4.0
  138. */
  139. public static boolean executeBatch(Class<?> entityClass, Log log, Consumer<SqlSession> consumer) {
  140. SqlSessionFactory sqlSessionFactory = sqlSessionFactory(entityClass);
  141. SqlSessionHolder sqlSessionHolder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sqlSessionFactory);
  142. boolean transaction = TransactionSynchronizationManager.isSynchronizationActive();
  143. if (sqlSessionHolder != null) {
  144. SqlSession sqlSession = sqlSessionHolder.getSqlSession();
  145. //原生无法支持执行器切换,当存在批量操作时,会嵌套两个session的,优先commit上一个session
  146. //按道理来说,这里的值应该一直为false。
  147. sqlSession.commit(!transaction);
  148. }
  149. SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
  150. if (!transaction) {
  151. log.warn("SqlSession [" + sqlSession + "] Transaction not enabled");
  152. }
  153. try {
  154. consumer.accept(sqlSession);
  155. //非事物情况下,强制commit。
  156. sqlSession.commit(!transaction);
  157. return true;
  158. } catch (Throwable t) {
  159. sqlSession.rollback();
  160. Throwable unwrapped = ExceptionUtil.unwrapThrowable(t);
  161. if (unwrapped instanceof RuntimeException) {
  162. MyBatisExceptionTranslator myBatisExceptionTranslator
  163. = new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true);
  164. throw Objects.requireNonNull(myBatisExceptionTranslator.translateExceptionIfPossible((RuntimeException) unwrapped));
  165. }
  166. throw ExceptionUtils.mpe(unwrapped);
  167. } finally {
  168. sqlSession.close();
  169. }
  170. }
  171. /**
  172. * 执行批量操作
  173. *
  174. * @param entityClass 实体类
  175. * @param log 日志对象
  176. * @param list 数据集合
  177. * @param batchSize 批次大小
  178. * @param consumer consumer
  179. * @param <E> T
  180. * @return 操作结果
  181. * @since 3.4.0
  182. */
  183. public static <E> boolean executeBatch(Class<?> entityClass, Log log, Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
  184. Assert.isFalse(batchSize < 1, "batchSize must not be less than one");
  185. return !CollectionUtils.isEmpty(list) && executeBatch(entityClass, log, sqlSession -> {
  186. int size = list.size();
  187. int i = 1;
  188. for (E element : list) {
  189. consumer.accept(sqlSession, element);
  190. if ((i % batchSize == 0) || i == size) {
  191. sqlSession.flushStatements();
  192. }
  193. i++;
  194. }
  195. });
  196. }
  197. /**
  198. * 批量更新或保存
  199. *
  200. * @param entityClass 实体
  201. * @param log 日志对象
  202. * @param list 数据集合
  203. * @param batchSize 批次大小
  204. * @param predicate predicate(新增条件) notNull
  205. * @param consumer consumer(更新处理) notNull
  206. * @param <E> E
  207. * @return 操作结果
  208. * @since 3.4.0
  209. */
  210. public static <E> boolean saveOrUpdateBatch(Class<?> entityClass, Class<?> mapper, Log log, Collection<E> list, int batchSize, BiPredicate<SqlSession,E> predicate, BiConsumer<SqlSession, E> consumer) {
  211. String sqlStatement = getSqlStatement(mapper, SqlMethod.INSERT_ONE);
  212. return executeBatch(entityClass, log, list, batchSize, (sqlSession, entity) -> {
  213. if (predicate.test(sqlSession, entity)) {
  214. sqlSession.insert(sqlStatement, entity);
  215. } else {
  216. consumer.accept(sqlSession, entity);
  217. }
  218. });
  219. }
  220. /**
  221. * 获取mapperStatementId
  222. *
  223. * @param sqlMethod 方法名
  224. * @return 命名id
  225. * @since 3.4.0
  226. */
  227. public static String getSqlStatement(Class<?> mapper, SqlMethod sqlMethod) {
  228. return mapper.getName() + StringPool.DOT + sqlMethod.getMethod();
  229. }
  230. }