4.12.5 Assigning the Primary Key Value Using an Oracle Sequence
As an alternative to using a trigger-assigned value (as described in Section 4.10.10, "How to Get Trigger-Assigned Primary Key Values from a Database Sequence"), you can assign the value to a primary key when creating a new row using an Oracle sequence. This metadata-driven approach allows you to centralize the code to retrieve the primary key into a single Java file that can be reused by multiple entity objects.Example 4-16 shows a simple
CustomEntityImpl
framework extension class on which the entity objects are based. Its overridden create()
method tests for the presence of a custom attribute-level metadata property named SequenceName
and if detected, populates the attribute's default value from the next number in that sequence.Example 4-16 CustomEntityImpl Framework Extension Class
package sample; import oracle.jbo.AttributeDef; import oracle.jbo.AttributeList; import oracle.jbo.server.EntityImpl; import oracle.jbo.server.SequenceImpl; public class CustomEntityImpl extends EntityImpl { protected void create(AttributeList attributeList) { super.create(attributeList); for (AttributeDef def : getEntityDef().getAttributeDefs()) { String sequenceName = (String)def.getProperty("SequenceName"); if (sequenceName != null) { SequenceImpl s = new SequenceImpl(sequenceName,getDBTransaction()); setAttribute(def.getIndex(),s.getSequenceNumber()); } } } }
To assign the primary key value using an Oracle sequence:
- Create the
CustomEntityImpl.java
file in your project, and insert the code shown in Example 4-16. - In the Application Navigator, double-click the entity you want to edit to open the overview editor.
- In the overview editor, click the Attributes tab, and double-click the attribute you want to edit.
- In the Edit Attribute dialog, set the attribute Type to Number, and then click the Custom Properties node.
- Enter
SequenceName
for the name. - Enter the name of the database sequence for the value, click Add, then click OK to create the custom property.
For example, aDept
entity could define the custom propertySequenceName
on itsDeptno
attribute with the valueDEPT_TABLE_SEQ
.
No comments:
Post a Comment