ServiceImpl.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /**
  2. * Copyright (c) 2011-2016, 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.service.impl;
  17. import java.io.Serializable;
  18. import java.util.List;
  19. import java.util.Map;
  20. import org.apache.ibatis.binding.MapperMethod;
  21. import org.apache.ibatis.logging.Log;
  22. import org.apache.ibatis.logging.LogFactory;
  23. import org.apache.ibatis.session.SqlSession;
  24. import org.springframework.beans.factory.annotation.Autowired;
  25. import org.springframework.transaction.annotation.Transactional;
  26. import com.baomidou.mybatisplus.entity.TableInfo;
  27. import com.baomidou.mybatisplus.enums.SqlMethod;
  28. import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
  29. import com.baomidou.mybatisplus.mapper.BaseMapper;
  30. import com.baomidou.mybatisplus.mapper.Condition;
  31. import com.baomidou.mybatisplus.mapper.SqlHelper;
  32. import com.baomidou.mybatisplus.mapper.Wrapper;
  33. import com.baomidou.mybatisplus.plugins.Page;
  34. import com.baomidou.mybatisplus.service.IService;
  35. import com.baomidou.mybatisplus.toolkit.CollectionUtils;
  36. import com.baomidou.mybatisplus.toolkit.MapUtils;
  37. import com.baomidou.mybatisplus.toolkit.ReflectionKit;
  38. import com.baomidou.mybatisplus.toolkit.StringUtils;
  39. import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
  40. /**
  41. * <p>
  42. * IService 实现类( 泛型:M 是 mapper 对象,T 是实体 , PK 是主键泛型 )
  43. * </p>
  44. *
  45. * @author hubin
  46. * @Date 2016-04-20
  47. */
  48. public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
  49. private static final Log logger = LogFactory.getLog(ServiceImpl.class);
  50. @Autowired
  51. protected M baseMapper;
  52. /**
  53. * <p>
  54. * 判断数据库操作是否成功
  55. * </p>
  56. * <p>
  57. * 注意!! 该方法为 Integer 判断,不可传入 int 基本类型
  58. * </p>
  59. *
  60. * @param result 数据库操作返回影响条数
  61. * @return boolean
  62. */
  63. protected static boolean retBool(Integer result) {
  64. return SqlHelper.retBool(result);
  65. }
  66. @SuppressWarnings("unchecked")
  67. protected Class<T> currentModelClass() {
  68. return ReflectionKit.getSuperClassGenricType(getClass(), 1);
  69. }
  70. /**
  71. * <p>
  72. * 批量操作 SqlSession
  73. * </p>
  74. */
  75. protected SqlSession sqlSessionBatch() {
  76. return SqlHelper.sqlSessionBatch(currentModelClass());
  77. }
  78. /**
  79. * 获取SqlStatement
  80. *
  81. * @param sqlMethod
  82. * @return
  83. */
  84. protected String sqlStatement(SqlMethod sqlMethod) {
  85. return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod());
  86. }
  87. @Transactional
  88. public boolean insert(T entity) {
  89. return retBool(baseMapper.insert(entity));
  90. }
  91. @Transactional
  92. public boolean insertAllColumn(T entity) {
  93. return retBool(baseMapper.insertAllColumn(entity));
  94. }
  95. @Transactional
  96. public boolean insertBatch(List<T> entityList) {
  97. return insertBatch(entityList, 30);
  98. }
  99. /**
  100. * 批量插入
  101. *
  102. * @param entityList
  103. * @param batchSize
  104. * @return
  105. */
  106. @Transactional
  107. public boolean insertBatch(List<T> entityList, int batchSize) {
  108. if (CollectionUtils.isEmpty(entityList)) {
  109. throw new IllegalArgumentException("Error: entityList must not be empty");
  110. }
  111. SqlSession batchSqlSession = sqlSessionBatch();
  112. try {
  113. int size = entityList.size();
  114. String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
  115. for (int i = 0; i < size; i++) {
  116. batchSqlSession.insert(sqlStatement, entityList.get(i));
  117. if (i >= 1 && i % batchSize == 0) {
  118. batchSqlSession.flushStatements();
  119. }
  120. }
  121. batchSqlSession.flushStatements();
  122. } catch (Throwable e) {
  123. throw new MybatisPlusException("Error: Cannot execute insertBatch Method. Cause", e);
  124. }
  125. return true;
  126. }
  127. /**
  128. * <p>
  129. * TableId 注解存在更新记录,否插入一条记录
  130. * </p>
  131. *
  132. * @param entity 实体对象
  133. * @return boolean
  134. */
  135. @Transactional
  136. public boolean insertOrUpdate(T entity) {
  137. if (null != entity) {
  138. Class<?> cls = entity.getClass();
  139. TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
  140. if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) {
  141. Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty());
  142. if (StringUtils.checkValNull(idVal)) {
  143. return insert(entity);
  144. } else {
  145. /*
  146. * 更新成功直接返回,失败执行插入逻辑
  147. */
  148. return updateById(entity) || insert(entity);
  149. }
  150. } else {
  151. throw new MybatisPlusException("Error: Can not execute. Could not find @TableId.");
  152. }
  153. }
  154. return false;
  155. }
  156. @Transactional
  157. public boolean insertOrUpdateBatch(List<T> entityList) {
  158. return insertOrUpdateBatch(entityList, 30);
  159. }
  160. @Transactional
  161. public boolean insertOrUpdateBatch(List<T> entityList, int batchSize) {
  162. if (CollectionUtils.isEmpty(entityList)) {
  163. throw new IllegalArgumentException("Error: entityList must not be empty");
  164. }
  165. SqlSession batchSqlSession = sqlSessionBatch();
  166. try {
  167. int size = entityList.size();
  168. for (int i = 0; i < size; i++) {
  169. insertOrUpdate(entityList.get(i));
  170. if (i >= 1 && i % batchSize == 0) {
  171. batchSqlSession.flushStatements();
  172. }
  173. }
  174. batchSqlSession.flushStatements();
  175. } catch (Throwable e) {
  176. throw new MybatisPlusException("Error: Cannot execute insertBatch Method. Cause", e);
  177. }
  178. return true;
  179. }
  180. @Transactional
  181. public boolean deleteById(Serializable id) {
  182. return retBool(baseMapper.deleteById(id));
  183. }
  184. @Transactional
  185. public boolean deleteByMap(Map<String, Object> columnMap) {
  186. if (MapUtils.isEmpty(columnMap)) {
  187. throw new MybatisPlusException("deleteByMap columnMap is empty.");
  188. }
  189. return retBool(baseMapper.deleteByMap(columnMap));
  190. }
  191. @Transactional
  192. public boolean delete(Wrapper<T> wrapper) {
  193. return retBool(baseMapper.delete(wrapper));
  194. }
  195. @Transactional
  196. public boolean deleteBatchIds(List<? extends Serializable> idList) {
  197. return retBool(baseMapper.deleteBatchIds(idList));
  198. }
  199. @Transactional
  200. public boolean updateById(T entity) {
  201. return retBool(baseMapper.updateById(entity));
  202. }
  203. @Transactional
  204. public boolean updateAllColumnById(T entity) {
  205. return retBool(baseMapper.updateAllColumnById(entity));
  206. }
  207. @Transactional
  208. public boolean update(T entity, Wrapper<T> wrapper) {
  209. return retBool(baseMapper.update(entity, wrapper));
  210. }
  211. @Transactional
  212. public boolean updateBatchById(List<T> entityList) {
  213. return updateBatchById(entityList, 30);
  214. }
  215. @Transactional
  216. public boolean updateBatchById(List<T> entityList, int batchSize) {
  217. if (CollectionUtils.isEmpty(entityList)) {
  218. throw new IllegalArgumentException("Error: entityList must not be empty");
  219. }
  220. SqlSession batchSqlSession = sqlSessionBatch();
  221. try {
  222. int size = entityList.size();
  223. String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID);
  224. for (int i = 0; i < size; i++) {
  225. MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
  226. param.put("et", entityList.get(i));
  227. batchSqlSession.update(sqlStatement, param);
  228. if (i >= 1 && i % batchSize == 0) {
  229. batchSqlSession.flushStatements();
  230. }
  231. }
  232. batchSqlSession.flushStatements();
  233. } catch (Throwable e) {
  234. throw new MybatisPlusException("Error: Cannot execute insertBatch Method. Cause", e);
  235. }
  236. return true;
  237. }
  238. public T selectById(Serializable id) {
  239. return baseMapper.selectById(id);
  240. }
  241. public List<T> selectBatchIds(List<? extends Serializable> idList) {
  242. return baseMapper.selectBatchIds(idList);
  243. }
  244. public List<T> selectByMap(Map<String, Object> columnMap) {
  245. return baseMapper.selectByMap(columnMap);
  246. }
  247. public T selectOne(Wrapper<T> wrapper) {
  248. return SqlHelper.getObject(baseMapper.selectList(wrapper));
  249. }
  250. public Map<String, Object> selectMap(Wrapper<T> wrapper) {
  251. return SqlHelper.getObject(baseMapper.selectMaps(wrapper));
  252. }
  253. public Object selectObj(Wrapper<T> wrapper) {
  254. return SqlHelper.getObject(baseMapper.selectObjs(wrapper));
  255. }
  256. public int selectCount(Wrapper<T> wrapper) {
  257. return SqlHelper.retCount(baseMapper.selectCount(wrapper));
  258. }
  259. public List<T> selectList(Wrapper<T> wrapper) {
  260. return baseMapper.selectList(wrapper);
  261. }
  262. @SuppressWarnings("unchecked")
  263. public Page<T> selectPage(Page<T> page) {
  264. return selectPage(page, Condition.EMPTY);
  265. }
  266. public List<Map<String, Object>> selectMaps(Wrapper<T> wrapper) {
  267. return baseMapper.selectMaps(wrapper);
  268. }
  269. public List<Object> selectObjs(Wrapper<T> wrapper) {
  270. return baseMapper.selectObjs(wrapper);
  271. }
  272. @SuppressWarnings({"rawtypes", "unchecked"})
  273. public Page<Map<String, Object>> selectMapsPage(Page page, Wrapper<T> wrapper) {
  274. SqlHelper.fillWrapper(page, wrapper);
  275. page.setRecords(baseMapper.selectMapsPage(page, wrapper));
  276. return page;
  277. }
  278. public Page<T> selectPage(Page<T> page, Wrapper<T> wrapper) {
  279. SqlHelper.fillWrapper(page, wrapper);
  280. page.setRecords(baseMapper.selectPage(page, wrapper));
  281. return page;
  282. }
  283. }