Database primary key generator java code

Source: Internet
Author: User

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;
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.exe cutesql (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 ++;
}
 
 

}

 

 

 

Call method: keygenerator. getinstance (). getnextkey (keyname );

 

 

Keyname is the table name.

 

 

Related database structure:

 

Table tb_key

 

The fields are as follows:

 

KeyValue: PK size

 

Keyname: Table Name

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.