1. 程式人生 > 程式設計 >java自動生成編號的實現(格式:yyMM+四位流水號)

java自動生成編號的實現(格式:yyMM+四位流水號)

本篇文章主要介紹了java自動生成編號的實現,分享給大家,具體如下

/**
 * 自動生成編號格式:yyMM+四位流水號
 */
 @RequestMapping(params = "createCode")
 @ResponseBody
 public AjaxJson createCode(HttpServletRequest request,String tableName,String fieldName) {
 AjaxJson j = new AjaxJson();
 
 String sql = "select Max(a." + fieldName + ") max_code from "
  + tableName + " a ";
 
 List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
 list = jdbcTemplate.queryForList(sql);
 // System.out.println("最大編號:"+list.get(0).get("max_comment_code"));
 String comment_code = ""; 
 String max_code = "";
 if (list.size() > 0) {
  max_code = (String) list.get(0).get("max_code");
 }
 
 SimpleDateFormat format = new SimpleDateFormat("yyMM"); // 時間字串產生方式
 String uid_pfix = format.format(new Date()); // 組合流水號前一部分,時間字串,如:1601
 System.out.println("time=" + format.format(new Date()));
 if (max_code != null && max_code.contains(uid_pfix)) {
  String uid_end = max_code.substring(4,8); // 擷取字串最後四位,結果:0001
  // System.out.println("uid_end=" + uid_end);
  int endNum = Integer.parseInt(uid_end); // 把String型別的0001轉化為int型別的1
  // System.out.println("endNum=" + endNum);
  int tmpNum = 10000 + endNum + 1; // 結果10002
  // System.out.println("tmpNum=" + tmpNum);
  comment_code = uid_pfix + UtilMethod.subStr("" + tmpNum,1);// 把10002首位的1去掉,再拼成1601260002字串
 } else {
  comment_code = uid_pfix + "0001";
 }
 // System.out.println(comment_code);
 
 Map<String,Object> map = new HashMap<String,Object>();
 map.put("msg",comment_code);
 j.setAttributes(map);
 return j;
 }
 
//公共方法
public class UtilMethod {
 
 
 /*
  * 把10002首位的1去掉的實現方法:
  * @param str
  * @param start
  * @return
  */
 public static String subStr(String str,int start) {
     if (str == null || str.equals("") || str.length() == 0)
       return "";
     if (start < str.length()) {
       return str.substring(start);
     } else {
       return "";
     }
 
   }
}

前端:

//自動生成編號;格式:yyMM0001
function createCode() {
  var id = $("[name='id']").val();
  // alert(id.length);
   if(id.length<=0){
  var a="";
  $.ajax({
   async : false,cache : false,type : 'POST',contentType : 'application/json',dataType:"json",url : "Controller.do?createCode&tableName=表名&fieldName=欄位名",error : function() {
   alert('出錯了');
   frameElement.api.close();
   },success : function(data) {
   a=data.attributes.msg;
   } 
   
 }); 
//alert(a);
    $("#check_task_code").val(a);
   }
 }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。