IdSequenceUtils.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.ruoyi.base.utils;
  2. import cn.hutool.core.date.DateUtil;
  3. import com.ruoyi.base.domain.BaseIdsequence;
  4. import com.ruoyi.base.service.IBaseIdsequenceService;
  5. import org.apache.commons.lang3.StringUtils;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Component;
  8. import java.util.Date;
  9. @Component
  10. public class IdSequenceUtils {
  11. @Autowired
  12. private IBaseIdsequenceService baseIdsequenceService;
  13. /**
  14. * 生成主键
  15. *
  16. * @param idName
  17. * @return
  18. */
  19. public String generateId(String idName) {
  20. int count = 20;
  21. while (count > 0) {
  22. count--;
  23. BaseIdsequence sysIdsequence = baseIdsequenceService.selectBaseIdsequenceByIdName(idName.toUpperCase());
  24. if (sysIdsequence == null) {
  25. return null;
  26. }
  27. String prefix;
  28. String dateStr = "";
  29. if (!StringUtils.isEmpty(sysIdsequence.getDateFormat()) && (sysIdsequence.getDateFormat().equals("YYYYMMDD") || sysIdsequence.getDateFormat().equals("YYMMDD"))) {
  30. prefix = sysIdsequence.getPrefix() + DateUtil.format(new Date(), "yMMdd");
  31. dateStr = DateUtil.format(new Date(), "yMMdd");
  32. } else {
  33. prefix = sysIdsequence.getPrefix();
  34. }
  35. int index = 0;
  36. if (sysIdsequence.getDateFormat() == null || sysIdsequence.getDateFormat().equals("") || dateStr.equals(sysIdsequence.getDateMax())) {
  37. index = sysIdsequence.getIdSequence() == null ? 0 : sysIdsequence.getIdSequence().intValue();
  38. }
  39. String resultNo = "";
  40. if (!StringUtils.isEmpty(prefix)) {
  41. resultNo = prefix + CommonUtils.lpad((index + 1) + "", sysIdsequence.getLength().intValue(), "0");
  42. } else {
  43. resultNo = (index + 1) + "";
  44. }
  45. //TODO 乐观锁的思想,一旦无法修改成功,返回0,但是20次之后就会出现返回''
  46. int isOk = baseIdsequenceService.updateByVersion(idName, dateStr, sysIdsequence.getIdSequence(), index + 1);
  47. if (isOk > 0) {
  48. return resultNo;
  49. }
  50. }
  51. return "";
  52. }
  53. public static void main(String[] args) {
  54. System.out.println(DateUtil.format(new Date(), "yMMdd"));
  55. }
  56. }