Thursday, September 15, 2011

Manually Generate Castor UUID Key

I am using Castor (Data binding framework) in my company. Most of the tables in our database have an UUID column to make sure all the records are unique. UUID column value is generated by Castor when we insert the record into that table. Of course you have to specific which table and column to store the UUID in the mapping file.

Sometimes you might want to manually insert the records into database. If you insert 1 or 2 records, you can easily specific the UUID value when insert. But if you have 100 or 1000 records to insert. How can you generate the UUID?

I have spent few hours to find out.

You can just copy generateKey method and write a java class to generate the insert statements you want.

Hope the below example can help you to kick start.

public final class ManuallyCastorGeneratorKeyUUID {

private DecimalFormat _df = new DecimalFormat();

private String _sHost = null;

private static long _staticCounter = 0;

// Method extracted from UUIDKeyGenerator

public String generateKey() {

String sUUID = null;

try {

// getting IP (fixed length: 12 character)

if(_sHost == null)

_sHost = InetAddress.getLocalHost().getHostAddress();

StringTokenizer st = new StringTokenizer(_sHost, ".");

_df.applyPattern("000");

while(st.hasMoreTokens()) {

if(sUUID == null)

sUUID = _df.format(new Integer(st.nextToken()));

else

sUUID += _df.format(new Integer(st.nextToken()));

}

// getting currentTimeMillis (fixed length: 13 character)

_df.applyPattern("0000000000000");

sUUID += _df.format(System.currentTimeMillis());

// getting static counter (fixed length: 15 character)

if(_staticCounter >= 99999) // 99999 generated keys in one timer interval? no...

_staticCounter = 0;

_staticCounter++;

_df.applyPattern("00000");

sUUID += _df.format(_staticCounter);

} catch ( Exception ex ) {

ex.printStackTrace();

}

return sUUID;

}

public static void main(String args[]) {

ManuallyCastorGeneratorKeyUUID g = new ManuallyCastorGeneratorKeyUUID();

for(int i=0; i<10; i++) {

System.out.println("insert into table (uuid, column1, column2) values ('" + g.generateKey() +"', value1, value2);");

}

}

}

No comments: