1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- package com.ruoyi.base.utils;
- import cn.hutool.core.date.DateUtil;
- import com.ruoyi.base.domain.BaseIdsequence;
- import com.ruoyi.base.service.IBaseIdsequenceService;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import java.util.Date;
- @Component
- public class IdSequenceUtils {
- @Autowired
- private IBaseIdsequenceService baseIdsequenceService;
- /**
- * 生成主键
- *
- * @param idName
- * @return
- */
- public String generateId(String idName) {
- int count = 20;
- while (count > 0) {
- count--;
- BaseIdsequence sysIdsequence = baseIdsequenceService.selectBaseIdsequenceByIdName(idName.toUpperCase());
- if (sysIdsequence == null) {
- return null;
- }
- String prefix;
- String dateStr = "";
- if (!StringUtils.isEmpty(sysIdsequence.getDateFormat()) && (sysIdsequence.getDateFormat().equals("YYYYMMDD") || sysIdsequence.getDateFormat().equals("YYMMDD"))) {
- prefix = sysIdsequence.getPrefix() + DateUtil.format(new Date(), "yMMdd");
- dateStr = DateUtil.format(new Date(), "yMMdd");
- } else {
- prefix = sysIdsequence.getPrefix();
- }
- int index = 0;
- if (sysIdsequence.getDateFormat() == null || sysIdsequence.getDateFormat().equals("") || dateStr.equals(sysIdsequence.getDateMax())) {
- index = sysIdsequence.getIdSequence() == null ? 0 : sysIdsequence.getIdSequence().intValue();
- }
- String resultNo = "";
- if (!StringUtils.isEmpty(prefix)) {
- resultNo = prefix + CommonUtils.lpad((index + 1) + "", sysIdsequence.getLength().intValue(), "0");
- } else {
- resultNo = (index + 1) + "";
- }
- //TODO 乐观锁的思想,一旦无法修改成功,返回0,但是20次之后就会出现返回''
- int isOk = baseIdsequenceService.updateByVersion(idName, dateStr, sysIdsequence.getIdSequence(), index + 1);
- if (isOk > 0) {
- return resultNo;
- }
- }
- return "";
- }
- public static void main(String[] args) {
- System.out.println(DateUtil.format(new Date(), "yMMdd"));
- }
- }
|