不一定要用synchronized。用数据库事务也可以,做成一个函数或一个存贮过程 begin transaction; index = select key from keyTable; index = index+1; update KeyTable set key = index; index = select key from keyTable; end transaction; return index; 为提高效率可以写成如下(应尽量用这个函数生成key,否则浪费编码空间): int getIndex(){ static bIsFirst = false; int currentIndex , maxIndex; if(IsFirst || (currentIndex == maxIndex)){ begin transaction; currentIndex = select key from keyTable; maxIndex = currentIndex+100;//或其它缓冲值 update KeyTable set key = maxIndex; maxIndex = select key from keyTable; end transaction; }//end if return ++currentIndex; }//end
在程序中可用Select语句读取。
可以用到单例和工厂模式写一个生成主键的类,对这个表进行synchronized操作,每次要insert时利用这个类生成键!
begin transaction;
index = select key from keyTable;
index = index+1;
update KeyTable set key = index;
index = select key from keyTable;
end transaction;
return index; 为提高效率可以写成如下(应尽量用这个函数生成key,否则浪费编码空间):
int getIndex(){
static bIsFirst = false;
int currentIndex , maxIndex;
if(IsFirst || (currentIndex == maxIndex)){
begin transaction;
currentIndex = select key from keyTable;
maxIndex = currentIndex+100;//或其它缓冲值
update KeyTable set key = maxIndex;
maxIndex = select key from keyTable;
end transaction;
}//end if
return ++currentIndex;
}//end
可以用到单例和工厂模式写一个生成主键的类,对这个表进行synchronized操作,每次要insert时利用这个类生成键!
--
同意