mysql生成主鍵


在mysql中,可以使用uuid 來生成主鍵,但是用mysql的uuid()函數 ,生成的uuid是36位的,其中包含32個字符以及4個分隔符(-),

往往這個分隔符對我們來說是沒有用的,可以使用mysql自帶的replace函數去掉分隔符

replace(uuid(),'-','')   ---->將uuid()中的‘-’,去掉,即替換成空串;

此外

upper(replace(uuid(),'-',''))用於將字符轉換為大寫

JAVA文件中也可生成UUID主鍵:

 

package ---;

import java.util.Random;
import java.util.UUID;

/**
 * 功能簡述:主鍵生成器,調用java util生成32位的 字符串
 * 
 * @author 
 * @version
 * 
 */
public class IdGenerator {

    /**
     * 
     * @return 32位的uuid
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 功能簡述:根據UUID生成10位訂單號
     * 
     * @return
     */
    public static String getOrderIdByUUID() {
        int hashCode = UUID.randomUUID().toString().hashCode();
        if (hashCode < 0) {
            hashCode = -hashCode;
        }
        // 0-前面補充0;10 代表長度為10;d代表參數為正數
        return String.format("%010d", hashCode);
    }

    // 生成4位提取碼
    public static int getCode() {
        Random random = new Random();
        int num = random.nextInt(900);
        num = num + 100;
        return num;
    }

    // 16位訂單流水號: 類型  + 時間戳 + 隨機3位數
    public static String generateOrderNo(String type) {
        return type + System.currentTimeMillis() + getCode();
    }

    public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
            "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0",
            "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
            "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y",
            "Z" };

    // 8位uuid
    public static String generateShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM