您好,登錄后才能下訂單哦!
/**
* 編碼生成器
*/
public abstract class AbstractNumberGenerator {
private int leastSerialNoLength = 6;
/**
* 生成編碼
* @return
*/
public String generateNumber() throws Exception {
return new StringBuilder().append(getPrefix()).append(getBusinessCode()).append(getWrapperSerialNo()).toString();
}
/**
* 前綴
* @return
*/
public abstract String getPrefix();
/**
* 業務碼
* @return
*/
public abstract String getBusinessCode();
/**
* 順序號
* @return
*/
public abstract int getSerialNo() throws Exception ;
/**
* 順序號最少位數
* @param length
*/
protected void setLeastSerialNo(int length){
this.leastSerialNoLength = length;
}
/**
* 順序號不足補位
* @return
*/
protected String getWrapperSerialNo() throws Exception {
String format = "%0"+ leastSerialNoLength +"d";
return String.format(format, getSerialNo());
}
}
/**
* 通過數據庫的索引機制,建表生成相關數據
*/
public class CustomerNumberCounterGenerator extends AbstractNumberGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerNumberCounterGenerator.class);
@Override
public String getPrefix() {
return "K";
}
@Override
public String getBusinessCode() {
return DateUtils.format(new Date(), "yyMMdd");
}
/**
* 獲取順序號。注:數據庫建立的唯一索引機制,獲取多并發的情況會報錯,因此嘗試第二次獲取。
* @return
* @throws Exception
*/
@Override
public int getSerialNo() throws Exception {
int serialNo = Integer.MIN_VALUE;
try {
serialNo = getCustomSerialNo();
} catch (Exception e) {
try {
serialNo = getCustomSerialNo();
} catch (Exception e1) {
throw new Exception("getSerialNo is failed.", e1);
}
}
return serialNo;
}
public int getCustomSerialNo() throws Exception {
String prefix = getPrefix();
String businessCode = getBusinessCode();
CustomerNumberCounter numberCounter = CustomerNumberCounter.findFirst(CustomerNumberCounter.class, "prefix=? and timeCode=?", new Object[]{prefix, businessCode});
if (null == numberCounter){
numberCounter = new CustomerNumberCounter();
numberCounter.setPrefix(prefix);
numberCounter.setTimeCode(businessCode);
numberCounter.setSerialNo(1);
numberCounter.create();
return 1;
}
try {
BaseDomain.beginTransaction(CustomerNumberCounter.class);
int execute = BaseDomain.execute(BaseDomain.class, "update t_customer_number_counter set serialNo = serialNo+1 where id = ?", new Object[]{numberCounter.getId()});
if (execute != 1)
throw new IllegalAccessException("更新計數器報錯");
return CustomerNumberCounter.find(CustomerNumberCounter.class, numberCounter.getId()).getSerialNo();
}catch (Exception e){
BaseDomain.rollback(CustomerNumberCounter.class);
if (LOGGER.isErrorEnabled())
LOGGER.error("to generate customer number occur error.", e);
}finally {
if (BaseDomain.getCurrentTransaction(CustomerNumberCounter.class) != null)
BaseDomain.commit(CustomerNumberCounter.class);
}
throw new IllegalAccessException("生成客戶編碼失敗");
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。