Tuesday, June 8, 2010

Entity object Primary Key in ADF(11.1.1.2.0) takes negative values from DB Sequence: Work Around

In my previous Blogs I have shown how to insert data into tables but one drawback of that example is the database design I had made. For sake of simplicity I had made the Primary Key Editable which leads to an impractical database design. In this blog I am trying to implement while inserting data into table each time we press create button, primary key of corresponding table is automatically uploaded from database sequence.

I have created a database table PROJECT_DETAILS as follows

  1. CREATE TABLE project_details(
  2. project_id VARCHAR2(12),

  3. project_name VARCHAR2(22),
  4. client_name VARCHAR2(30),
  5. description VARCHAR2(50),
  6. startdate DATE,
  7. enddate DATE,
  8. software_used VARCHAR2(50))); --Add primary Kry
  9. ALTER TABLE project_details ADD CONSTRAINT proj_pk PRIMARY KEY(project_id); --Create Sequence
  10. create sequence PROJ_SEQ increment by 1 start with 1000;

In fact Oracle ADF has the flexibility to use database sequence, while creating entity object we can set value of Primary key as DBSequence.



Doule Click on Project ID will lead to a screen where you can specify whether this ProjectId will act like a noramal string and editable or takes automatically uploaded DBSequence value from database.



But while testing It always takes negative Sequence Number as we press "create Another Button".

 

As a work around I have overridden the create method in Entity Implementation java class ( ProjectEntityObjectImpl . java ) like below.
Algorithm:

//Getting reference of all Attributes belongs to the entity
  1. protected void create( AttributeList attributeList){
  2. super . create (attributeList);
  3. AttributeDef[] attrArray = getStructureDef() . getAttributeDefs() ;
  4. AttributeDef attr = null; //Traverse through the array to get hold of primary key Attribute
  5. for ( int currIndex=0;currIndex<=attrArray. length ();currIndex++){ //If primary key found then move out from loop after give that reference to attribute definition.
  6. if (attrArray[currIndex]. isPrimaryKey() )
  7. {attr = attrArray[currIndex];
  8. break ;}
  9. } //Hold index of the primary key attribute
  10. int index= attr. getIndex (); //Hold sequence name
  11. String sequence = "PROJ_SEQ"; //Create SequenceImpl object using database sequence name.
  12. SequenceImpl seq = new SequenceImpl (sequence, getDBTransaction ()); //Set Attribute value
  13. setAttributeInternal (index, new DBSequence (seq. getSequenceNumber() ));}

While testing the same in Browser it takes 1048 automatically from sequence and Thus we can achieve that Primary key should not be in editable format.

No comments:

Post a Comment