SqlRunner.java 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. * Copyright (c) 2011-2025, 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.assist.ISqlRunner;
  18. import com.baomidou.mybatisplus.core.metadata.IPage;
  19. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
  20. import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
  21. import org.apache.ibatis.logging.Log;
  22. import org.apache.ibatis.logging.LogFactory;
  23. import org.apache.ibatis.parsing.GenericTokenParser;
  24. import org.apache.ibatis.session.SqlSession;
  25. import org.apache.ibatis.session.SqlSessionFactory;
  26. import org.mybatis.spring.SqlSessionUtils;
  27. import org.springframework.transaction.annotation.Transactional;
  28. import java.util.HashMap;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Optional;
  32. /**
  33. * SqlRunner 执行 SQL
  34. *
  35. * @author Caratacus
  36. * @since 2016-12-11
  37. */
  38. public class SqlRunner implements ISqlRunner {
  39. private static final Log LOG = LogFactory.getLog(SqlRunner.class);
  40. // 单例Query
  41. public static final SqlRunner DEFAULT = new SqlRunner();
  42. private Class<?> clazz;
  43. public SqlRunner() {
  44. }
  45. public SqlRunner(Class<?> clazz) {
  46. this.clazz = clazz;
  47. }
  48. /**
  49. * 获取默认的SqlQuery(适用于单库)
  50. *
  51. * @return ignore
  52. */
  53. public static SqlRunner db() {
  54. return DEFAULT;
  55. }
  56. /**
  57. * 根据当前class对象获取SqlQuery(适用于多库)
  58. *
  59. * @param clazz ignore
  60. * @return ignore
  61. */
  62. public static SqlRunner db(Class<?> clazz) {
  63. return new SqlRunner(clazz);
  64. }
  65. @Transactional
  66. @Override
  67. public boolean insert(String sql, Object... args) {
  68. SqlSession sqlSession = sqlSession();
  69. try {
  70. return SqlHelper.retBool(sqlSession.insert(INSERT, sqlMap(sql, args)));
  71. } finally {
  72. closeSqlSession(sqlSession);
  73. }
  74. }
  75. @Transactional
  76. @Override
  77. public boolean delete(String sql, Object... args) {
  78. SqlSession sqlSession = sqlSession();
  79. try {
  80. return SqlHelper.retBool(sqlSession.delete(DELETE, sqlMap(sql, args)));
  81. } finally {
  82. closeSqlSession(sqlSession);
  83. }
  84. }
  85. /**
  86. * 获取sqlMap参数
  87. *
  88. * @param sql 指定参数的格式: {0}, {1}
  89. * @param args 仅支持String
  90. * @return ignore
  91. */
  92. private Map<String, Object> sqlMap(String sql, Object... args) {
  93. Map<String, Object> sqlMap = getParams(args);
  94. sqlMap.put(SQL, parse(sql));
  95. return sqlMap;
  96. }
  97. /**
  98. * 获取执行语句
  99. *
  100. * @param sql 原始sql
  101. * @return 执行语句
  102. */
  103. private String parse(String sql) {
  104. return new GenericTokenParser("{", "}", content -> "#{" + content + "}").parse(sql);
  105. }
  106. /**
  107. * 获取参数列表
  108. *
  109. * @param args 参数
  110. * @return 参数map
  111. * @since 3.5.12
  112. */
  113. private Map<String, Object> getParams(Object... args) {
  114. if (args != null) {
  115. Map<String, Object> params = CollectionUtils.newHashMapWithExpectedSize(args.length);
  116. for (int i = 0; i < args.length; i++) {
  117. params.put(String.valueOf(i), args[i]);
  118. }
  119. return params;
  120. }
  121. return new HashMap<>();
  122. }
  123. /**
  124. * 获取sqlMap参数
  125. *
  126. * @param sql 指定参数的格式: {0}, {1}
  127. * @param page 分页模型
  128. * @param args 仅支持String
  129. * @return ignore
  130. */
  131. private Map<String, Object> sqlMap(String sql, IPage<?> page, Object... args) {
  132. Map<String, Object> sqlMap = getParams(args);
  133. sqlMap.put(PAGE, page);
  134. sqlMap.put(SQL, parse(sql));
  135. return sqlMap;
  136. }
  137. @Transactional
  138. @Override
  139. public boolean update(String sql, Object... args) {
  140. SqlSession sqlSession = sqlSession();
  141. try {
  142. return SqlHelper.retBool(sqlSession.update(UPDATE, sqlMap(sql, args)));
  143. } finally {
  144. closeSqlSession(sqlSession);
  145. }
  146. }
  147. /**
  148. * 根据sql查询Map结果集
  149. * <p>SqlRunner.db().selectList("select * from tbl_user where name={0}", "Caratacus")</p>
  150. *
  151. * @param sql sql语句,可添加参数,格式:{0},{1}
  152. * @param args 只接受String格式
  153. * @return ignore
  154. */
  155. @Override
  156. public List<Map<String, Object>> selectList(String sql, Object... args) {
  157. SqlSession sqlSession = sqlSession();
  158. try {
  159. return sqlSession.selectList(SELECT_LIST, sqlMap(sql, args));
  160. } finally {
  161. closeSqlSession(sqlSession);
  162. }
  163. }
  164. /**
  165. * 根据sql查询一个字段值的结果集
  166. * <p>注意:该方法只会返回一个字段的值, 如果需要多字段,请参考{@code selectList()}</p>
  167. *
  168. * @param sql sql语句,可添加参数,格式:{0},{1}
  169. * @param args 只接受String格式
  170. * @return ignore
  171. */
  172. @Override
  173. public List<Object> selectObjs(String sql, Object... args) {
  174. SqlSession sqlSession = sqlSession();
  175. try {
  176. return sqlSession.selectList(SELECT_OBJS, sqlMap(sql, args));
  177. } finally {
  178. closeSqlSession(sqlSession);
  179. }
  180. }
  181. /**
  182. * 根据sql查询一个字段值的一条结果
  183. * <p>注意:该方法只会返回一个字段的值, 如果需要多字段,请参考{@code selectOne()}</p>
  184. *
  185. * @param sql sql语句,可添加参数,格式:{0},{1}
  186. * @param args 只接受String格式
  187. * @return ignore
  188. */
  189. @Override
  190. public Object selectObj(String sql, Object... args) {
  191. return SqlHelper.getObject(LOG, selectObjs(sql, args));
  192. }
  193. @Override
  194. public long selectCount(String sql, Object... args) {
  195. SqlSession sqlSession = sqlSession();
  196. try {
  197. return SqlHelper.retCount(sqlSession.<Long>selectOne(COUNT, sqlMap(sql, args)));
  198. } finally {
  199. closeSqlSession(sqlSession);
  200. }
  201. }
  202. @Override
  203. public Map<String, Object> selectOne(String sql, Object... args) {
  204. return SqlHelper.getObject(LOG, selectList(sql, args));
  205. }
  206. @Override
  207. public <E extends IPage<Map<String, Object>>> E selectPage(E page, String sql, Object... args) {
  208. if (null == page) {
  209. return null;
  210. }
  211. SqlSession sqlSession = sqlSession();
  212. try {
  213. page.setRecords(sqlSession.selectList(SELECT_LIST, sqlMap(sql, page, args)));
  214. } finally {
  215. closeSqlSession(sqlSession);
  216. }
  217. return page;
  218. }
  219. /**
  220. * 获取Session 默认自动提交
  221. */
  222. private SqlSession sqlSession() {
  223. return SqlSessionUtils.getSqlSession(getSqlSessionFactory());
  224. }
  225. /**
  226. * 释放sqlSession
  227. *
  228. * @param sqlSession session
  229. */
  230. private void closeSqlSession(SqlSession sqlSession) {
  231. SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
  232. }
  233. /**
  234. * 获取SqlSessionFactory
  235. */
  236. private SqlSessionFactory getSqlSessionFactory() {
  237. return Optional.ofNullable(clazz).map(GlobalConfigUtils::currentSessionFactory).orElse(SqlHelper.FACTORY);
  238. }
  239. /**
  240. * @deprecated 3.5.3.2
  241. */
  242. @Deprecated
  243. public void close() {
  244. }
  245. }