数据库主键生成器java代码

package com.aspboy.base.database.util;

import java.util.HashMap;

public class KeyGenerator
{
private static KeyGenerator keygen=new KeyGenerator();
private static final int POOL_SIZE=20;
private HashMap keylist=new HashMap(10);
private KeyGenerator()
{}

public static KeyGenerator getInstance()
{
return keygen;
}
public synchronized int getNextKey(String keyName)
{
KeyInfo keyinfo;
if (keylist.containsKey(keyName))
{
keyinfo=(KeyInfo)keylist.get(keyName);
System.out.println("key found");
}
else
{
keyinfo=new KeyInfo(POOL_SIZE,keyName);
keylist.put(keyName, keyinfo);
System.out.println("new key created");
}
return keyinfo.getNextKey();
}

}

package com.aspboy.base.database.util;

import com.aspboy.base.database.DBBean;

public class KeyInfo
{
private int keyMax;
private int Keymin;
private int nextKey;
private int poolSize;
private String keyName;
//private int times ;

public KeyInfo(int poolSize,String keyName)
{
this.poolSize=poolSize;
this.keyName=keyName;
loadFromDB();
//times++;
//System.out.println("get keyvalue from db tiems=="+times);

}

public int getKeyMax() {
return keyMax;
}

public int getKeymin() {
return Keymin;
}

private void loadFromDB()
{
String sql1="update tb_key set KeyValue=KeyValue+"+poolSize+" where keyName='"+keyName+"'";
DBBean.executeSql(sql1);
String sql2="select KeyValue from tb_key where keyName='"+keyName+"'";
int keyFromDB=DBBean.getIntSingle(sql2);
keyMax=keyFromDB;
Keymin=keyFromDB-poolSize+1;
nextKey=Keymin;
}

public int getNextKey() {

if (nextKey>keyMax)
{
loadFromDB();
System.out.println("get keyvalue from db");

}
return nextKey++;
}

}

调用方法: KeyGenerator.getInstance().getNextKey(keyName);

keyName 为表名称

相关数据库结构:

表tb_key

字段如下:

KeyValue:pk大小

keyName:表名

你可能感兴趣的:(java)