在实际的使用中发现不是所有表设计都是使用例如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;
}