IdUtils.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package com.boman.system.utils;
  2. import com.boman.common.core.utils.SpringUtils;
  3. import com.boman.common.redis.RedisKey;
  4. import com.boman.common.redis.service.RedisService;
  5. import com.boman.gen.domain.GenTableColumn;
  6. import com.boman.system.mapper.StandardlyMapper;
  7. import org.apache.commons.collections.CollectionUtils;
  8. import java.util.List;
  9. import static com.boman.common.core.utils.obj.ObjectUtils.requireNonNull;
  10. /**
  11. * @author shiqian
  12. * @description
  13. * @date 2021年03月23日 16:04
  14. **/
  15. public class IdUtils {
  16. public static Long getMaxId(String tableName, String pkName) {
  17. RedisService redisService = SpringUtils.getBean(RedisService.class);
  18. String sequencesKey = RedisKey.SEQ + tableName.toUpperCase();
  19. boolean isExist = redisService.exists(sequencesKey);
  20. if (isExist) {
  21. return redisService.increment(sequencesKey);
  22. }
  23. // 查数据库
  24. StandardlyMapper mapper = SpringUtils.getBean(StandardlyMapper.class);
  25. Long maxId = mapper.selectMaxId(tableName, pkName);
  26. if (null == maxId || maxId <= 0) {
  27. maxId = 1L;
  28. redisService.setCacheObject(sequencesKey, maxId);
  29. } else {
  30. redisService.increment(sequencesKey, ++maxId);
  31. }
  32. return maxId;
  33. }
  34. public static String getPkName(List<GenTableColumn> columnList) {
  35. if (CollectionUtils.isEmpty(columnList)) {
  36. throw new IllegalArgumentException("获取主键失败");
  37. }
  38. for (GenTableColumn tableColumn : columnList) {
  39. if ("1".equalsIgnoreCase(tableColumn.getIsPk())) {
  40. return requireNonNull(tableColumn.getColumnName(), "主键名称为空");
  41. }
  42. }
  43. throw new IllegalArgumentException("获取主键失败");
  44. }
  45. }