Java:String类型的有序Id批量生成器

it2022-05-05  151

做项目的时候免不了对数据库进行批量操作,比如说批量增加一批产品,批量增加一批工号。而这时候我们对于所增加的对象的自编号自然是不可能从页面由客户自己对一个个自编号进行手动输入,这样当所需要的编号达到一定数值之后就会造成极大的负担。但是将所需要增加的数量传过来由工具自动生成就很棒了。 以下就是一个Id批量生成器,有需要的朋友直接拿去用就可以了:

import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class IdGenerator { private Long currentdbidscount; private List<String> ids = new ArrayList<String>(); private String idpre; private String yearstr; private String idafter; public IdGenerator() { } public Long getCurrentdbidscount() { return currentdbidscount; } public void setCurrentdbidscount(Long currentdbidscount) { this.currentdbidscount = currentdbidscount; if (null == this.ids) { this.ids = new ArrayList<String>(); } } public List<String> getIds() { return ids; } public void setIds(List<String> ids) { this.ids = ids; } public String getIdpre() { return idpre; } public void setIdpre(String idpre) { this.idpre = idpre; } public String getYearstr() { return yearstr; } public void setYearstr(String yearstr) { this.yearstr = yearstr; } public String getIdafter() { return idafter; } public void setIdafter(String idafter) { this.idafter = idafter; } public List<String> initIds(Long ocounts) { for (int i = 0; i < ocounts; i++) { this.ids.add(getIdPre() + yearStr() + getIdAfter(i)); } return this.ids; } // private String getIdAfter(int addcount) { // 默认生成 xx1700001 //这里是数字部分长度 int goallength = 5; //获取数据库纵向+1次循环(addcount) int count = this.currentdbidscount.intValue() + 1 + addcount; StringBuilder sBuilder = new StringBuilder(""); //计算与五位数的差值ֵ int length = goallength - new String(count + "").length(); for (int i = 0; i < length; i++) { sBuilder.append("0"); } sBuilder.append(count + ""); return sBuilder.toString(); } private String getIdPre() { // idpre==null?this.idpre="xx":this.idpre=idpre; this.idpre = "Id-Hello-"; return this.idpre; } private String yearStr() { Date currentdate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String yearstr = sdf.format(currentdate).substring(2, 4); return yearstr; } public void clear() { this.ids = null; } @Override public String toString() { return "IdGenerator [ids=" + ids + "]"; } }

下面来看看我的测试效果: 建议在哪里调用这个就把它写成一个内部类 。


最新回复(0)