The IdGenerator
interface includes methods for generating IDs that are strings or longs:
generateLongId(String pIdSpace)
generateStringId(String pIdSpace)
When you want to get a new ID, use these IdGenerator
methods of the interface.
Normally, applications access the standard ID generator service at /atg/dynamo/service/IdGenerator
, which starts up when your application is started. The following examples demonstrate how to use IdGenerator
APIs in order to construct and use an ID generator. You can see these examples in context in the sample class located at:
<ATG11dir>/DAS/src/Java/atg/service/idgen/sample/Example1.java
First, construct an IdGenerator
and get some IDs. You do not need to specify a name for the IdSpace
; the default IdSpace
is used:
TransientIdGenerator gen = new TransientIdGenerator(); gen.initialize(); for (int i=0; i<3; i++) { gen.generateLongId(); }
Generating an ID
The next line shows how you might generate a long ID in an IdSpace
named foo
. With the IdGenerator
component’s autoCreate
property set to true, as it is by default, you do not have to create the foo
IdSpace
—it is created automatically:
gen.generateLongId("foo");
Given a seed of 1, this generates the ID 1.
Creating an IdSpace
In most cases, your application uses the SQLIdGenerator
and configure IdSpaces
for it in an XML configuration file. The following example shows how to create an IdSpace
using the Java API:
IdSpace barSpace = new IdSpace("bar", // name of id space 100, // starting id (seed) "Bar", // prefix null); // suffix gen.addIdSpace(barSpace);
Generating More IDs
Now, let’s generate more IDs in the bar
and foo
IdSpaces
:
gen.generateLongId("bar"); //generates ID=100 gen.generateLongId("bar"); //generates ID=101 // see how the "foo" space is independent of the bar space gen.generateLongId("foo"); //generates ID=2
Generating String IDs
Now generate some String
IDs. String IDs use the prefix
and suffix
properties of the IdSpace
. These properties are not consulted when long IDs are generated. Within an IdSpace
, the same pool of IDs is used for String and long IDs.
gen.generateStringId("bar"); //generates ID=Bar102 gen.generateStringId("bar"); //generates ID=Bar103 gen.generateStringId("bar"); //generates ID=Bar104 gen.generateLongId("bar"); //generates ID=105 gen.generateLongId("bar"); //generates ID=106 gen.generateStringId("bar"); //generates ID=Bar107
IdGeneratorException
IdGenerator
methods throw the checked exception IdGeneratorException
. This exception indicates an ID cannot be generated. Common causes include database trouble for the SQLIdGenerator
and asking for an ID in a name space that does not exist when autoCreate
is false
. Production applications should catch this exception. The following example forces an exception for demonstration purposes:
gen.setAutoCreate(false); try { gen.generateStringId("bogus"); } catch (IdGeneratorException ige) { System.out.println("rats, couldn't get an id"); ige.printStackTrace(); }