java非数据库自增的主键

在实际的使用中发现不是所有表设计都是使用例如mysql的自增来完成的
我在使用oracle中发现没法很好的使用其自增来完成主键,所以这边我自己简单的设计了一套主键的生成规则:head + yyyyMMddHHmmssSSS + 主键标识 +4位树
其中主键标识(放置在配置文件中)是多机使用的;区别那台机器生成

主要方法

public class PrimaryKeyTool {

    public static SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyyMMddHHmmssSSS");

    /**
     * 主键标识 每台机器不一样的标识 不要重复,配置在config.properties中
     * 防止多机生成重复
     */
    public static String  primaryKeyMark = Config.get("PRIMARY_KEY_Mark");
    /**
     * 生成各个表的主键(head + yyyyMMddHHmmssSSS + 主键标识 +4位树)
     * 
     * @Description:
     * @param head
     * @return: String
     * @special_use:
     */
    public static String getPrimaryKey(String head) {
        Date date = new Date();
        String time = sdf.format(date);
        StringBuffer primaryKey = new StringBuffer();
        primaryKey.append(head).append(time).append(primaryKeyMark).append(MyRandom.getRandom());
        return primaryKey.toString();
    }

}

辅助方法

public class MyRandom {
    /**
     * 随机数
     */
    private static String random;

    /**
     * 随机数的库 (保证不重复即可)
     */
    private static List<String> list;
    static {
        init();
    }

    /**
     * 初始化,生成10000个数
     */
    private static void init() {
        list = new ArrayList<String>();
        for (int i = 9999; i >= 0; i--) {
            list.add(Tools.convertNum(i, 4));
        }
    }

    /**
     * 得到随机数
     * 
     * @return
     */
    public synchronized static String getRandom() {
        if (list == null || list.size() <= 0) {
            init();
        }
        int size = list.size() - 1;
        random = list.get(list.size() - 1);
        list.remove(size);
        return random;
    }

    public static void main(String[] args) {
        // MyRandom myRandom = new MyRandom();
        for (int i = 99; i >= 0; i--) {
            //list.add(Tools.convertNum(i, 4));
            System.out.println(i);
        }
    }
}
/**
     * 转换成指定位数的字符串,不够的用0补齐
     * 
     * @param num
     *            数字
     * @param size
     *            位数
     * @return
     * @example convertNum(123,6) <br/>
     *          结果为 000123
     */
    public static String convertNum(int num, int size) {
        String str = String.format("%0" + size + "d", num);
        return str;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值