db4o 解决自动生成主键的问题 分享下初步想法

db4o 解决自动生成主键的问题 分享下初步想法
欢迎指点。
由于Db4o 数据库没有类似sequence的东西,而自带的.ext().getUID()不是稳定的,在refragement数据库后会发生变化,所以自己必须实现个,但考虑到这个系列必须持久化。

我使用的方法是 系统时间long + 一个小范围的递增数字
这里的+ 不是加法,是追加位数,类似十进制数字的左移。

因为如果单单使用系统时间,在并发度高的情况下,long是必定会重复的,就算synchorinzed, Thread.sleep(1)都没有用处,何况在n核的服务器上。

源码如下:


package com.glt.util;

import java.util.Date;

import org.apache.log4j.Logger;

/**
* 将此类作为系统的唯一系列号生产器
* 0. 生成规则 new Date().getTime()*10 + 1位递增数(0-9)。 10为扩展基数
* 1. 即扩展位数! 这样此类无需持久化!!
* 2. 存在的问题: 如果机器性能足够地高,以至于EXTRA=10000时,仍然会出现重复的UUID,此方法无效了。
* @author Guolt_ecc
* */
public class SequenceGenerator {
//扩展基数
private static int EXTRA=10;

private long test= 1217603186953L; //默认的日期只有13w
private long test1=12176031876401L;
private long test2=121760318764011L;
private long test3=1217603187640110323L; //long 18位

private static final Logger log=Logger.getLogger("com.glt.util.SequenceGenerator");

//shortID 取值范围[0,EXTRA)
private static int sID=0;


public static synchronized long getUID(){
long preID=new Date().getTime();
++sID;
if(sID==EXTRA){
sID=0;
}
return preID*EXTRA+sID;

}


}

多谢分享,这么重要的功能db4o不应该忽视:

ID Generators
A set of default ID Generators should be included with db4o and these could also be pluggable with a user's own implementation by using a config method such as: config().objectClass().objectField().idField(new CustomIdGenerator())

AutoIncrementIdGenerator - DEFAULT - (unique per class, not globally unique, starts at 1 and increments for each object of a particular class)
TimeStampIdGenerator
InternalIdGenerator (uses internal db4o object id)
GUIDIdGenerator

http://developer.db4o.com/ProjectSpaces/view.aspx/Db4o_Product_Design/ID_Systems