Using database sequences as primary key with ADF Business Components
Written By: Pascal Alma on December 28, 2006
One Comment
Last week I was going over some code I used at a former project. In this project we used ADF Business Components (10.1.2) as business layer (it also works for 10.1.3). All our database tables had an ID column (number) as primary key and each table had his own sequence to be used to create the ID.
We decided to implement the use of the sequence in our Entity object. We created a base class 'BaseEntityImpl' with the following code:
JAVA:
-
/**
-
* Overriden method
-
* This version sets the sequence of the primary key if the name of
-
* the sequence is provided with the entity object's attribute.
-
*
-
* @param nameValuePair
-
*/
-
{
-
super.create(nameValuePair);
-
-
AttributeDef ad = getSinglePrimaryKey();
-
if (ad != null)
-
{
-
// Now check if an sequence name is provided. If so, take this
-
// sequence value
-
setAttributeFromSequence(ad.getIndex(), seqName);
-
}
-
}
-
-
/**
-
* Gets the attribute defintion that is defined as primary key for
-
* the entity.
-
* WARNING: Will return the first attribute it encounters when a multi-field
-
* primary key is defined!
-
* @return AttributeDefinition that is marked as primary key
-
*/
-
private AttributeDef getSinglePrimaryKey()
-
{
-
_log.debug(method);
-
-
AttributeDef result = null;
-
AttributeDef[] adArray = getStructureDef().getAttributeDefs();
-
for (int i = 0; i <adArray.length; i++)
-
{
-
if (adArray[i].isPrimaryKey())
-
{
-
result = adArray[i];
-
break;
-
}
-
}
-
return result;
-
}
-
-
/**
-
* Use incoming sequence name to generate value for attribute
-
*
-
* @param sequence
-
* @param index
-
*/
-
{
-
_log.debug(method);
-
-
if (!StringUtils.isEmpty(sequence))
-
{
-
SequenceImpl seq = new SequenceImpl(sequence, getDBTransaction());
-
setAttributeInternal(index, new DBSequence(seq.getSequenceNumber()));
-
}
-
}
When we create a business component with the corresponding wizard we used the following settings:

And for the primary key column we set the following properties:


So now every time a new row is created in the Entity Object the sequence is used to generate the new ID for that row.
Tags: Oracle JHeadstart










[...] step. 2. The employeeId is now always set to -1, you will need to something more fancy here (see this post for example). After we have added this method and it compiles, we have to do one more thing and [...]