Thursday, February 20, 2014

Multiple ways for populating DB Sequence to an attribute in an Entity Object

Hello All,

Here in this post, I will show multiple ways to populate DB Sequence to an attribute in an Entity Object.

Technique 1 : Setting Groovy in the default value of the attribute

Set the default value for the attribute as an expression value set as follows : 

(new oracle.jbo.server.SequenceImpl("SEQ_NAME", adf.object.getDBTransaction())).getSequenceNumber()

Note : Make sure you select expression in the "Value Type" property for the attribute.

Technique 2 : Use create() method of the [Entity]Impl class



Then in the corresponding [Entity]Impl class, you need to write these java statements and pass your sequence name. 

protected void create(AttributeList attributeList) {
    super.create(attributeList);
    SequenceImpl seq = new SequenceImpl("SEQ_NAME", getDBTransaction());
    setDepartmentId(seq.getSequenceNumber());
}

Technique 3 : Use groovy expression to call customMethod created in [Entity]Impl class

Create a custom Method which again has the same implementation as used in create() method in Technique 2

    public Number createSeq(String seq_name) {
        Number seq_no = new Number(0);
        SequenceImpl seq = new SequenceImpl(seq_name, getDBTransaction());
        seq_no = seq.getSequenceNumber();
        return seq_no;

    }

Then we need to call this method from the value property in the attribute by passing the sequence name and make sure you selected "Expression" in "Value Type" of the attribute.



Technique 4 : Using DBTrigger to populate the Sequence on Commit

First create a trigger on the table. The below screenshot depicts how we create a trigger from SQL Developer declaratively. 


You can also see the script the IDE generates automatically. 


Once you create the trigger, you follow the below steps.
a. First change the attribute type to DBSequence and Refresh after Update for the attribute as shown below.

Now you can run your application and test. 

The advantages of the last technique is that even if the user don't want to continue and if the transaction is rolled back, the sequence number is not wasted unlike the other three techniques. 

Please let me know if you have any questions on this post. 

No comments:

Post a Comment