Cascading parent/child inserts while avoiding uniqueness constraints

Assume that I have two classes that I'd like to persist: MyObject and
InternalObject. MyObject has an InternalObject field. That is, MyObject is
the parent, InternalObject is the child in this one-to-one relationship.
Steps involved:
1) Enable ForeignKeyConstraints property in kodo.properties. That is add
the line,
kodo.jdbc.ForeignKeyConstraints=true
2) In package.jdo, add the following kodo extensions for MyObject's
InternalObject field mapping, i.e., io in my case.
<field name="io" default-fetch-group="false">
<extension vendor-name="kodo" key="jdbc-delete-action"
value="cascade"/>
<extension vendor-name="kodo" key="dependent" value="true"/>
</field>
The reasons that we have done these steps: we'd like kodo to properly
re-order the sql statements if necessary in order not to violate
parent/child dependencies during insertion, and also force cascading
deletes in case we delete the parent object.
Now comes the bulk of the algorithm.
String sKey // key of the object to insert
String sValue //value of the object to insert
MyObject o = new MyObject(sKey, sValue);
InternalObject io = new InternalObject(sKey,sValue); //using same values :)
o.setInternalObject(io); //parent-child relation
Object id = ((PersistenceCapable) o).jdoNewObjectIdInstance();
((PersistenceCapable)o).jdoCopyKeyFieldsToObjectId(id);
kpm.currentTransaction().begin();
try {
Object trio = kpm.getObjectById(id, true);
kpm.deletePersistent(trio);
kpm.flush(); //apply deletes on the datastore
} catch (ObjectNotFoundException oe) {
System.out.println("First time!");
kpm.makePersistent(o);
kpm.currentTransaction().commit();

If this is a question, the extension you have is only a directive to
mappingtool to create cascade foreign keys. However, at runtime Kodo
will rely upon the foreign key definitions in the schema. You should
verify that the foreign key exists as you like in the schema. If you
want to have child relationships to be deleted, you should use the
dependent and element-dependent extensions.
Ahmet Bulut wrote:
Assume that I have two classes that I'd like to persist: MyObject and
InternalObject. MyObject has an InternalObject field. That is, MyObject is
the parent, InternalObject is the child in this one-to-one relationship.
Steps involved:
1) Enable ForeignKeyConstraints property in kodo.properties. That is add
the line,
kodo.jdbc.ForeignKeyConstraints=true
2) In package.jdo, add the following kodo extensions for MyObject's
InternalObject field mapping, i.e., io in my case.
<field name="io" default-fetch-group="false">
<extension vendor-name="kodo" key="jdbc-delete-action"
value="cascade"/>
<extension vendor-name="kodo" key="dependent" value="true"/>
</field>
The reasons that we have done these steps: we'd like kodo to properly
re-order the sql statements if necessary in order not to violate
parent/child dependencies during insertion, and also force cascading
deletes in case we delete the parent object.
Now comes the bulk of the algorithm.
String sKey // key of the object to insert
String sValue //value of the object to insert
MyObject o = new MyObject(sKey, sValue);
InternalObject io = new InternalObject(sKey,sValue); //using same values :)
o.setInternalObject(io); //parent-child relation
Object id = ((PersistenceCapable) o).jdoNewObjectIdInstance();
((PersistenceCapable)o).jdoCopyKeyFieldsToObjectId(id);
kpm.currentTransaction().begin();
try {
Object trio = kpm.getObjectById(id, true);
kpm.deletePersistent(trio);
kpm.flush(); //apply deletes on the datastore
} catch (ObjectNotFoundException oe) {
System.out.println("First time!");
kpm.makePersistent(o);
kpm.currentTransaction().commit();
Steve Kim
[email protected]
SolarMetric Inc.
http://www.solarmetric.com

Similar Messages

  • Parent-Child post order exception; FK constraint violation

    I've seen the discussion and answer recently in this forum for configuring BC4J
    to post the parent first, then the child, to avoid the FK constraint exception??
    So I have to appologise for re-asking, but I can't get the search function to find
    any thing that needs multiple key words. :(
    I've got two Entities, parent child, with Links, and Association between them on the FK.
    What was the trick to get the framework to correctly post the parent first??
    I've looked over the FkLink and FkAssoc and all these components are included by
    the AppModule...
    Thanks, curt

    Edit the association object between your parent and child entities and set the "Composition" flag (Composite Assocation in the UI), to true. You may elect to enforce "CascadeDelete" option, if you have database Cascade-delete turned on between the associated tables and want to avoid multiple DMLs for the details.

  • PK with TIMESTAMP causes insert unique constraint error at DST switch

    Hi,
    I have a test that inserts rows in a table that has a TIMESTAMP in its PK.
    When inserting rows that cross over the November DST change, it tries to insert these dates:
    --- Sun Nov 02 02:00:00 EST 2008
    --- Sun Nov 02 01:00:00 EST 2008
    --- Sun Nov 02 01:00:00 EDT 2008
    This is the output of 3 different UTC dates. We can see that there are 2 x 1am, but they differ in their DST. They are really 3 different UTC dates.
    But I get this error:
    --- Expected error: ORA-00001: unique constraint (DDLTEST1.SYS_C00142622) violated
    But I can get around that error and can insert these same dates if I set my JVM to UTC. The inserts work so I suspect this to be a JDBC issue.
    I am using the Oracle Thin driver in a spring app:
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@localhost:db" />
    I can post the sample code but wonder if there is an obvious answer to this.
    Note that MySql had the same problem. I fixed it by specifying the UTC timezone in the connection string, like this:
    jdbc:mysql://[host]/[db]?useLegacyDatetimeCode=false&useTimezone=true&sessionVariables=time_zone='UTC'
    Any idea how to get around that problem without setting JVM to UTC ?
    Claude
    Edited by: user2678899 on 10 juin 2009 10:09
    I removed #2 work around which was wrong
    Edited by: user2678899 on 10 juin 2009 10:23

    Timur Akhmadeev wrote:
    Hi,
    I suspect this to be a JDBC issue.Nope, this is your schema design gap. It breaks the main principle of PK: to uniquely identify a row in a table always. Your PK doesn't satisfy it, since it depends on client's settings.Why is setting the JVM to UTC working ? This is the part that confuses me.
    I create the 3 dates in Eastern time, then change the JVM default to UTC: the 3 inserts work.
    I create the 3 dates in Eastern time, then leave the JVM to Eastern time , the 3rd insert gets the unique constraint error.
    To me, the PK principle is not broken: these are 3 different UTC dates.

  • QA_RESULTS_INTERFACE, entring parent-child records.

    I am unable to create parent - child relationships while using QA_RESULTS_INTERFACE and import program.

    I am unable to create parent - child relationships while using QA_RESULTS_INTERFACE and import program.

  • Composite unique constraint on parent and child values?

    Is it possible to have a composite unique constraint containing values from child elements? The below example has the 'child' elements are out-of-line but this is preferred but optional, as I know you cannot have a unique constraint across tables without having a reference table containing the constraint and both columns. How does xdb handle this requirement?
    allowed:
    <parent ID="1">
       <child><name>test1</name></child>
       <child><name>test2</name></child>
    </parent>
    <parent ID="2">
       <child><name>test1</name></child>
       <child><name>test2</name></child>
    </parent>not allowed:
    <parent ID="1">
       <child><name>test1</name></child>
       <child><name>test1</name></child>
    </parent>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:xdb="http://xmlns.oracle.com/xdb"
               xdb:storeVarrayAsTable="true"
               elementFormDefault="qualified">
        <xs:element name="parent" type="Parent_T"
            xdb:columnProps="CONSTRAINT parent_pkey PRIMARY KEY (XMLDATA.ID)"
            xdb:defaultTable="PARENT"/>
        <xs:complexType name="Parent_T" xdb:SQLType="PARENT_T" xdb:maintainDOM="false">
            <xs:sequence>
                <xs:element name="child" type="Child_T" minOccurs="1" maxOccurs="unbounded" xdb:SQLName="CHILD"
                          xdb:SQLInline="false" xdb:defaultTable="CHILD" "/>
            </xs:sequence>
            <xs:attribute name="ID" xdb:SQLName="ID" use="required" />
        </xs:complexType>
        <xs:complexType name="Child_T" xdb:SQLType="CHILD_T">
           <xs:sequence>
             <xs:element name="name" type="xs:string" xdb:SQLName="NAME"/>
           </xs:sequence>
         </xs:complexType>    
    </xs:schema>xdb:columnProps="CONSTRAINT parent_pkey PRIMARY KEY (XMLDATA.ID),*UNIQUE(XMLDATA.CHILD.NAME)*" raises nonexistant attribute
    One possible solution would be to copy the value of the parent primary key to the child element, then I could create a composite unique constraint using only values from the child. However, I have this same requirement elsewhere in my schema nested further down, and it may become messy / bad design having to cascade all the primary keys down the schema. For example I have a recursive element in which two attributes need to be unique only within the parent:
    <parent id="1">
       <child a="1" b="1">
          <child a="1" b="2">
             <child a="1" b="1" /> *not allowed
          </child>
       </child>
       <child a="1" b="2" /> *not allowed
    </parent>Possible fix:
    <child a="1" b="2" parent_id="1" />
    <xs:complexType name="Child_T>
       <xs:sequence>
          <xs:element name="child" xsd:SQLInline="false" xsd:columnProps="UNIQUE(XMLDATA.a,XMLDATA.b,XMLDATA.parent_id)" minOccurs="0" maxOccurs="unbounded" type="Child_T">
       </xs:sequence>
       </xs:element
    </xs:complexType>Is there a better design?
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production                          
    CORE     10.2.0.4.0     Production                                      
    TNS for Linux: Version 10.2.0.4.0 - Production                  
    NLSRTL Version 10.2.0.4.0 - Production

    You can do something like this :
    SQL> DECLARE
      2 
      3    xsd_doc xmltype := xmltype('<?xml version="1.0" encoding="utf-8"?>
      4  <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb">
      5    <xs:element name="name" xdb:SQLType="VARCHAR2">
      6      <xs:simpleType>
      7        <xs:restriction base="xs:string">
      8          <xs:maxLength value="30"/>
      9        </xs:restriction>
    10      </xs:simpleType>
    11    </xs:element>
    12    <xs:element name="child" xdb:SQLType="CHILD_T">
    13      <xs:complexType xdb:SQLType="CHILD_T" xdb:maintainDOM="false">
    14        <xs:sequence>
    15          <xs:element ref="name"/>
    16        </xs:sequence>
    17      </xs:complexType>
    18    </xs:element>
    19    <xs:element name="parent" xdb:SQLType="PARENT_T">
    20      <xs:complexType xdb:SQLType="PARENT_T" xdb:maintainDOM="false">
    21        <xs:sequence>
    22          <xs:element ref="child" maxOccurs="unbounded" xdb:SQLCollType="CHILD_COLL"/>
    23        </xs:sequence>
    24        <xs:attribute name="ID" type="xs:integer" use="required"/>
    25      </xs:complexType>
    26    </xs:element>
    27    <xs:element name="root" xdb:defaultTable="MY_XML_TABLE" xdb:SQLType="ROOT_T">
    28      <xs:complexType xdb:SQLType="ROOT_T" xdb:maintainDOM="false">
    29        <xs:sequence>
    30          <xs:element ref="parent" maxOccurs="unbounded" xdb:SQLCollType="PARENT_COLL"/>
    31        </xs:sequence>
    32      </xs:complexType>
    33    </xs:element>
    34  </xs:schema>');
    35 
    36  BEGIN
    37 
    38    dbms_xmlschema.registerSchema(
    39      schemaURL => 'test_parent.xsd',
    40      schemaDoc => xsd_doc,
    41      local => true,
    42      genTypes => true,
    43      genbean => false,
    44      genTables => false,
    45      enableHierarchy => dbms_xmlschema.ENABLE_HIERARCHY_NONE
    46    );
    47 
    48  END;
    49  /
    PL/SQL procedure successfully completed
    SQL> CREATE TABLE my_xml_table OF XMLTYPE
      2  XMLTYPE STORE AS OBJECT RELATIONAL
      3  XMLSCHEMA "test_parent.xsd"
      4  ELEMENT "root"
      5  VARRAY xmldata."parent" STORE AS TABLE my_parent_tab
      6  (
      7    VARRAY "child" STORE AS TABLE my_child_tab
      8  )
      9  ;
    Table created
    SQL> ALTER TABLE my_parent_tab ADD CONSTRAINT parent_uk UNIQUE (nested_table_id, "ID");
    Table altered
    SQL> ALTER TABLE my_child_tab ADD CONSTRAINT child_uk UNIQUE (nested_table_id, "name");
    Table altered
    Then :
    SQL> insert into my_xml_table values (
      2  xmltype('<root><parent ID="1">
      3     <child><name>test1</name></child>
      4     <child><name>test2</name></child>
      5  </parent>
      6  <parent ID="1">
      7     <child><name>test1</name></child>
      8     <child><name>test2</name></child>
      9  </parent></root>')
    10  );
    insert into my_xml_table values (
    ERREUR à la ligne 1 :
    ORA-00001: violation de contrainte unique (DEV.PARENT_UK)
    SQL> insert into my_xml_table values (
      2  xmltype('<root><parent ID="1">
      3     <child><name>test1</name></child>
      4     <child><name>test1</name></child>
      5  </parent>
      6  <parent ID="2">
      7     <child><name>test1</name></child>
      8     <child><name>test2</name></child>
      9  </parent></root>')
    10  );
    insert into my_xml_table values (
    ERREUR à la ligne 1 :
    ORA-00001: violation de contrainte unique (DEV.CHILD_UK)
    SQL> insert into my_xml_table values (
      2  xmltype('<root><parent ID="1">
      3     <child><name>test1</name></child>
      4     <child><name>test2</name></child>
      5  </parent>
      6  <parent ID="2">
      7     <child><name>test1</name></child>
      8     <child><name>test2</name></child>
      9  </parent></root>')
    10  );
    1 ligne créée.http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14259/xdb06stt.htm#sthref987

  • ORA-00001:Unique Constraint while inserting 2 similar records from source

    Hi,
    in TEST1 there are records:
    10 20 ABC
    10 20 DEF
    I amt trying to insert into TEST which has CODE as Primary Key.
    declare
    type cur is ref cursor;
    cur_t cur;
    type v_t is table of TEST%rowtype;
    tab v_t;
    v_act_cnt_str VARCHAR2(4000);
    v_act_cnt NUMBER:=0;
    BEGIN
    v_act_cnt_str:=' SELECT COUNT(*) '||' FROM TEST '||' WHERE '||'('||CODE||')'||' IN '||'('||'SELECT '||CODE||' FROM TEST1'||')';
    DBMS_OUTPUT.PUT_LINE('The Actual Count String is'||v_act_cnt_str);
    EXECUTE IMMEDIATE v_act_cnt_str INTO v_act_cnt;
    open cur_t for select * from TEST1 ORDER BY ROWNUM;
    loop
    fetch cur_t bulk collect into tab limit 10000;
    if v_act_cnt=0 THEN
    forall i in 1..tab.count
    insert into TEST values tab(i);
    commit;
    ELSE
    v_merge_act_str :=
    'MERGE INTO TEST '||
    ' DEST' || ' USING TEST1 '||
    ' SRC' || ' ON (' || DEST.CODE=SRC.CODE || ')' ||
    ' WHEN MATCHED THEN ';
    first_str := 'UPDATE ' || ' SET ' ||
    'DEST.NAME=SRC.NAME,DEST.DEPT_NAME=SRC.DEPT_NAME;
    execute immediate v_merge_act_str || first_str;
    v_merge_act_str := '';
    first_str := '';
    commit;
    END IF;
    end loop;
    END;
    ITS GIVING ERROR as:
    ORA-00001: unique constraint (PK_TEST1) violated
    Any help will be needful for me
    Edited by: user598986 on Sep 22, 2009 4:20 AM
    Edited by: user598986 on Sep 22, 2009 4:22 AM

    Your code makes absolutely no sense whatsover. The whole point of MERGE is that it allows us to conditionally apply records from a source table as inserts or updates to a target table. So why have you coded two separate statements? And why are you using such horrible dynamic SQL?
    Sorry to unload on you, but you seem to have your code unnecessarily complicated, and that it turn makes it unnecessarily harder to debug. As an added "bonus" this approach will also perform considerably slower than a single MERGE statement. SQL is all about set operations. Don't do anything procedurally which can be done in a set.
    Cheers, APC
    blog: http://radiofreetooting.blogspot.com

  • Error while adding Image: ORA-00001: unique constraint

    Dear all,
    I have an error while adding images to MDM I can´t explain. I want to add 7231 images. About 6983 run fine. The rest throws this error.
    Error: Service 'SRM_MDM_CATALOG', Schema 'SRMMDMCATALOG2_m000', ERROR CODE=1 ||| ORA-00001: unique constraint (SRMMDMCATALOG2_M000.IDATA_6_DATAID) violated
    Last CMD: INSERT INTO A2i_Data_6 (PermanentId, DataId, DataGroupId, Description_L3, CodeName, Name_L3) VALUES (:1, :2, :3, :4, :5, :6)
    Name=PermanentId; Type=9; Value=1641157; ArraySize=0; NullInd=0;
    Name=DataId; Type=5; Value=426458; ArraySize=0; NullInd=0;
    Name=DataGroupId; Type=4; Value=9; ArraySize=0; NullInd=0;
    Name=Description_L3; Type=2; Value=; ArraySize=0; NullInd=0;
    Name=CodeName; Type=2; Value=207603_Img8078_gif; ArraySize=0; NullInd=0;
    Name=Name_L3; Type=2; Value=207603_Img8078.gif; ArraySize=0; NullInd=0;
    Error: Service 'SRM_MDM_CATALOG', Schema 'SRMMDMCATALOG2_m000', ERROR CODE=1 ||| ORA-00001: unique constraint (SRMMDMCATALOG2_M000.IDATA_6_DATAID) violated
    Last CMD: INSERT INTO A2i_Data_6 (PermanentId, DataId, DataGroupId, Description_L3, CodeName, Name_L3) VALUES (:1, :2, :3, :4, :5, :6)
    Name=PermanentId; Type=9; Value=1641157; ArraySize=0; NullInd=0;
    Name=DataId; Type=5; Value=426458; ArraySize=0; NullInd=0;
    Name=DataGroupId; Type=4; Value=9; ArraySize=0; NullInd=0;
    Name=Description_L3; Type=2; Value=; ArraySize=0; NullInd=0;
    Name=CodeName; Type=2; Value=207603_Img8085_gif; ArraySize=0; NullInd=0;
    Name=Name_L3; Type=2; Value=207603_Img8085.gif; ArraySize=0; NullInd=0;
    I checked all data. There is no such dataset in the database. Can anybody give me a hint how to avoid this error.
    One thing I wonder: The PermanentId is allways the same but I can´t do anything here.
    BR
    Roman
    Edited by: Roman Becker on Jan 13, 2009 12:59 AM

    Hi Ritam,
    For such issues, can you please create a new thread or directly email the author rather than dragging back up a very old thread, it is unlikely that the resolution would be the same as the database/application/etc releases would most probably be very different.
    For now I will close this thread as unanswered.
    SAP SRM Moderators.

  • Insert called before delete in a collection with unique constraint

    Hi all,
    I have a simple @OneToMany private mapping:
    private Collection<Item> items;
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    public Collection<Item> getItems() {
    return items;
    public void setItems(Collection<Item> items) {
    this.items = items;
    public void customize(ClassDescriptor classDescriptor) throws Exception {
    OneToManyMapping mapping = (OneToManyMapping)
    classDescriptor.getMappingForAttributeName("items");
    mapping.privateOwnedRelationship();
    I have a unique constraint on my Items table that a certain value cannot be duplicated.
    My problem appears when I remove a previously saved item from the collection and add a new item containing the same data, at the same time.
    After I save the parent and do a flush, I receive SQLIntegrityConstraintViolationException because TopLink performs first an insert query instead of deleting the existing item.
    I tested the application and everything went fine with: remove item / save parent / insert item / save parent
    I checked on the Internet and the documentation but didn't find anything similar to my problem. I tried debugging TopLink's internal calls but I'm missing some general ideas about all the inner workings and don't know what to look for. I use TopLink version: Oracle TopLink Essentials - 2.1 (Build b60e-fcs (12/23/2008))
    Does anyone have a hint of what to look for?
    Edited by: wise_guybg on Sep 25, 2009 4:01 PM
    Edited by: wise_guybg on Oct 5, 2009 11:22 AM

    Thank you for the suggestions James
    As I mentioned briefly I have done some debugging but couldn't understand how collections are updated. What I did find out is that setShouldPerformDeletesFirst() doesn't come into play in this case because this is not a consecutive change on entities.
    What I have in my case is a collection inside an entity that the user has tampered with and now TopLink has to do a merge. I cannot call flush() in the middle since the user has not approved that the changes made to the entity should be saved.
    I see that for TopLink it's not easy to figure out the order in which changes were made to a collection. Here is pseudo-code of when the constraint is touched:
    entity.items.remove(a)
    entity.items.add(b)
    merge(entity)
    And here is code that executes without a problem:
    entity.items.remove(a)
    merge(entity)
    entity.items.add(b)
    merge(entity)
    So once again, I think that collection changes are managed differently but I don't find a way to tell TopLink how to handle them. Any ideas?

  • How to update parent and child tables while updating parent table

    I have a parent table EMPLOYEE which includes columns (sysid, serviceno,employeename...) sysid is Primary key, serviceno is Unique key and I have child table DEPENDENT includes columns (sysid,employee_sysid,name,dob...) here again SYSID is primary key for DEPENDENTS table, employee_sysid is Foreign key of EMPLOYEE table.
    Now I want to change SYSID (using sequence) in EMPLOYEE table which need to be update in DEPENDENTS table as well
    Note: I have 10000 records in EMPLOYEE table as well as I have 5 more child tables which need to update new SYSID.
    please help me

    first disable the FOREIGN KEY Constraints.
    you can update Parent as well as Child record also with help of trigger.
    here i am giving you one examlpe..it may help u.
    create table parent(id number primary key,name varchar2(100))
    create table child_1(id number primary key,p_id number,dob date,
    CONSTRAINT FK_id FOREIGN KEY (p_id) REFERENCES parent (ID))
    create table child_2(id number primary key,p_id2 number,addr varchar2(1000),
    CONSTRAINT FK_id2 FOREIGN KEY (p_id2) REFERENCES parent (ID))
    insert some test data to parent and child tables.
    alter table child_2 disable constraint FK_id2
    alter table child_1 disable constraint FK_id2
    CREATE OR REPLACE TRIGGER delete_child
    BEFORE UPDATE ON parent
    FOR EACH ROW
    BEGIN
    UPDATE CHILD_1
    SET P_ID=:NEW.ID
    WHERE P_ID=:OLD.ID;
    UPDATE CHILD_2
    SET P_ID2 =:NEW.ID
    WHERE P_ID2=:OLD.ID;
    END;
    then Upadte parent table primary key col and check the child tables.
    then enable the constraints...

  • Avoiding uniquekey constraint while updating.

    hi gurus,
    i have the following table with unique constraint on it. i want to update or insert data by avoiding uniquekey constraint(do not disable while doing it).
    drop table test_1;
    create table test_1
      test1_seq_no  NUMBER not null,
      hdr_id    NUMBER(12) not null,
      rank              NUMBER(4) not null,
      id_versn_cd    VARCHAR2(8)  not null,
      id_seq_no        NUMBER(12) not null,
    constraint test_1_uniq unique(hdr_id,rank,id_versn_cd)
    insert into test_1 (TEST1_SEQ_NO, HDR_ID, RANK, ID_VERSN_CD, ID_SEQ_NO)
    values (1, 121, 1, '9', 111);
    insert into test_1 (TEST1_SEQ_NO, HDR_ID, RANK, ID_VERSN_CD, ID_SEQ_NO)
    values (2, 121, 2, '9', 112);
    insert into test_1 (TEST1_SEQ_NO, HDR_ID, RANK, ID_VERSN_CD, ID_SEQ_NO)
    values (3, 121, 3, '9', 113);
    insert into test_1 (TEST1_SEQ_NO, HDR_ID, RANK, ID_VERSN_CD, ID_SEQ_NO)
    values (4, 121, 4, '9', 114);
    commit;
    5
    1
    121
    1
    9
    111
    4
    2
    121
    2
    9
    112
    3
    3
    121
    3
    9
    113
    2
    4
    121
    4
    9
    114
    1
    5
    121
    5
    9
    115
    for above example i want to insert new row  with
    insert into test_1 (TEST1_SEQ_NO, HDR_ID, RANK, ID_VERSN_CD, ID_SEQ_NO)
    values (6, 121, 2, '9', 116);
    it should insert new row with rank 2. overriding the old rank.(meaning  id_seq_no 116 should take rank 2) when new rank comes in for id_seq_no 112 our program should update new rank. help is appreciated.

    CREATE TABLE "UNIQUE_TEST"
      ( "HDR_ID" NUMBER,
    "RANKING" NUMBER,
    "ID_VERSN_CD" CHAR(1),
    "ID_SEQ_NO" NUMBER,
    CONSTRAINT "UNIQUE_TEST_CON" UNIQUE ("HDR_ID", "RANKING", "ID_VERSN_CD") ENABLE
    select *
      from unique_test
    HDR_ID
    RANKING
    ID_VERSN_CD
    ID_SEQ_NO
    121
    1
    9
    111
    121
    2
    9
    112
    121
    3
    9
    113
    121
    4
    9
    114
    121
    5
    9
    115
    merge into unique_test ut
    using (select 121 HDR_ID,2 RANKING,'9' ID_VERSN_CD,116 ID_SEQ_NO
             from dual
           union all
           select HDR_ID,RANKING + 1,ID_VERSN_CD,ID_SEQ_NO
             from unique_test
            where ranking >= (select ranking
                                from (select 121 HDR_ID,2 RANKING,'9' ID_VERSN_CD,116 ID_SEQ_NO
                                        from dual
          ) x
       on (ut.ID_SEQ_NO = x.ID_SEQ_NO)
    when matched
    then update
             set ut.ranking = x.ranking
    when not matched
    then insert
          values (x.HDR_ID,x.RANKING,x.ID_VERSN_CD,x.ID_SEQ_NO)
    5 row(s) updated.
    select *
      from unique_test
    order by ranking
    HDR_ID
    RANKING
    ID_VERSN_CD
    ID_SEQ_NO
    121
    1
    9
    111
    121
    2
    9
    116
    121
    3
    9
    112
    121
    4
    9
    113
    121
    5
    9
    114
    121
    6
    9
    115
    Regards
    Etbin

  • Unique constraint violation while updating a non PK column

    Hi,
    I seem to have found this strange error.
    What I try to do is bulk fetch a cursor in some table arrays. with limit of 1000
    Then using a forall and a save exceptions at the end
    I update a table with the values inside one of the table arrays.
    The column I update is not part of a PK
    I catch the error message: ORA-24381
    by using PRAGMA exception_init(dml_errors, -24381);
    and later on :
    WHEN dml_errors THEN
    errors := SQL%BULK_EXCEPTIONS.COUNT;
    FOR i IN 1..sql%BULK_EXCEPTIONS.count LOOP
    lr_logging.parameters:= 'index = ' || sql%BULK_EXCEPTIONS(i).error_index || 'error = ' ||Sqlerrm(-sql%BULK_EXCEPTIONS(i).error_code) ;
    END LOOP;
    I insert these errors in another table. and i get 956 errors
    first one is :
    index = 3error = ORA-00001: unique constraint (.) violated
    last one is
    index = 1000error = ORA-00001: unique constraint (.) violated
    How can this be.Since i don't update in a PKcolumn.
    FULL CODE IS:
    PROCEDURE Update_corr_values( as_checkdate_from IN VARCHAR2,
    as_checkdate_until IN VARCHAR2,
    as_market IN VARCHAR2
    IS
    LS_MODULE_NAME CONSTANT VARCHAR2(30) := 'update_values';
    lr_logging recon_logging.logrec;
    CURSOR lc_update IS
    SELECT /*+ORDERED*/c.rowid,c.ralve_record_id,d.value,c.timestamp,f.value
    FROM rcx_allocated_values a,
    rcx_allocated_values b,
    meter_histories e,
    rcx_allocated_lp_value c,
    rcx_allocated_lp_value d,
    counter_values f
    WHERE a.slp_type NOT IN ('S89', 'S88', 'S10', 'S30') --AELP
    AND b.slp_type IN ('S89', 'S88') --residu
    AND a.valid_from >= to_date(as_checkdate_from,'DDMMYYYY HH24:MI')
    AND a.valid_to <= to_date(as_checkdate_until,'DDMMYYYY HH24:MI')
    AND a.market = as_market
    AND a.market = b.market
    AND a.ean_sup = b.ean_sup
    AND a.ean_br = b.ean_br
    AND a.ean_gos = b.ean_gos
    AND a.ean_dgo = b.ean_dgo
    AND a.direction = b.direction
    AND a.valid_from = b.valid_from
    AND a.valid_to = b.valid_to
    AND c.ralve_record_id = a.record_id
    AND d.ralve_record_id = b.record_id
    AND c.TIMESTAMP = d.TIMESTAMP
    AND e.ASSET_ID = 'KCF.SLP.' || a.SLP_TYPE
    --AND f.timestamp between to_date(gs_checkdate_from,'ddmmyyyy') and to_Date(as_checkdate_until,'ddmmyyyy')
    AND e.SEQ = f.MHY_SEQ
    AND f.TIMESTAMP =c.timestamp - 1/24
    ORDER BY c.rowid;
    TYPE t_value IS TABLE OF RCX_ALLOCATED_LP_VALUE.VALUE%TYPE;
    TYPE t_kcf IS TABLE OF COUNTER_VALUES.VALUE%TYPE;
    TYPE t_timestamp IS TABLE OF RCX_ALLOCATED_LP_VALUE.TIMESTAMP%TYPE;
    TYPE t_ralverecord_id IS TABLE OF RCX_ALLOCATED_LP_VALUE.RALVE_RECORD_ID%TYPE;
    TYPE t_row IS TABLE OF UROWID;
    ln_row t_row :=t_row();
    lt_value t_value := t_Value();
    lt_kcf t_kcf := t_kcf();
    lt_timestamp t_timestamp := t_timestamp();
    lt_ralve t_ralverecord_id := t_ralverecord_id();
    v_bulk NUMBER := 1000;
    val number;
    kcf number;
    ralve number;
    times date;
    dml_errors EXCEPTION;
    errors NUMBER;
    PRAGMA exception_init(dml_errors, -24381);
    BEGIN
    --setting arguments for the logging record
    lr_logging.module := LS_MODULE_NAME;
    lr_logging.context := 'INFLOW_ALL_VALUES_PARTS';
    lr_logging.logged_by := USER;
    lr_logging.parameters := 'Date time started: ' || TO_CHAR(sysdate,'DD/MM/YYYY HH24:MI');
    -- log debugs
    recon_logging.set_logging_env (TRUE, TRUE);
    recon_logging.log_event(lr_logging,'D');
    OPEN lc_update;
    LOOP
    FETCH lc_update BULK COLLECT INTO ln_row,lt_ralve,lt_value,lt_timestamp,lt_kcf LIMIT v_bulk;
    FORALL i IN NVL(lt_value.first,1)..NVL(lt_value.last,0) SAVE EXCEPTIONS
    UPDATE RCX_ALLOCATED_LP_VALUE
    SET VALUE = VALUE * lt_value(i) * lt_kcf(i)
    WHERE rowid =ln_row(i);
    COMMIT;
    lt_value.delete;
    lt_timestamp.delete;
    lt_ralve.delete;
    lt_kcf.delete;
    ln_row.delete;
    EXIT WHEN lc_update%NOTFOUND;
    END LOOP;
    CLOSE lc_update;
    recon_logging.log_event(lr_logging,'D');
    lr_logging.parameters := 'Date time ended: ' || TO_CHAR(sysdate,'DD/MM/YYYY HH24:MI');
    recon_logging.log_event(lr_logging,'D');
    --to be sure
    COMMIT;
    EXCEPTION
    WHEN dml_errors THEN
    recon_logging.set_logging_env(TRUE,TRUE);
    lr_logging.module := 'updatevalues';
    lr_logging.context := 'exception';
    lr_logging.logged_by := USER;
    lr_logging.parameters := 'in dml_errors';
    recon_logging.log_event(lr_logging);
    errors := SQL%BULK_EXCEPTIONS.COUNT;
    lr_logging.parameters:=errors;
    recon_logging.log_event(lr_logging);
    lr_logging.parameters :=('Number of errors is ' || errors);
    --DBMS_OUTPUT.PUT_LINE('Number of errors is ' || errors);
    FOR i IN 1..sql%BULK_EXCEPTIONS.count LOOP
    lr_logging.parameters:= 'index = ' || sql%BULK_EXCEPTIONS(i).error_index || 'error = ' ||Sqlerrm(-sql%BULK_EXCEPTIONS(i).error_code) ;
    recon_logging.log_event(lr_logging);
    END LOOP;
    --recon_logging.set_logging_env(TRUE,TRUE);
    --recon_logging.log_event(lr_logging);
    commit;
    WHEN OTHERS THEN
    lr_logging.module := 'updatevalues';
    lr_logging.context := 'exception';
    lr_logging.logged_by := USER;
    recon_logging.set_logging_env(TRUE,TRUE);
    lr_logging.parameters := 'in others error=' || SQLERRM;
    recon_logging.log_event(lr_logging);
    commit;--to look which is truly the last (else only commit after 1000)
    --raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
    END Update_corr_values;

    Hi,
    No I didn't update a unique constraint.
    But I found out that there is a trigger that causes the unique constraint while updating in the table.
    Silly mistake.Didn't know there was a trigger there.
    Thx anyway.
    Greetz

  • Unique Constraint error while executing statspack.snap procedure

    The following is the error which popped up when i was trying to execute statspack.snap procedure from perfstat user:
    ORA-00001: unique constraint (PERFSTAT.STATS$LATCH_CHILDREN_PK) violated
    ORA-06512: at "PERFSTAT.STATSPACK", line 1619
    ORA-06512: at "PERFSTAT.STATSPACK", line 71
    ORA-06512: at line 1
    How could i resolve such a problem, as all the constraints and objects for this user are created while running the oracle supplied script 'spcreate.sql'.
    If any 1 knows how to handle such a situation , can come forward n please help me out.

    SQL> execute statspack.snap (i_snap_level=>10);
    ERROR at line 1:
    ORA-00001: unique constraint (PERFSTAT.STATS$LATCH_CHILDREN_PK) violated
    ORA-06512: at "PERFSTAT.STATSPACK", line 1619
    ORA-06512: at "PERFSTAT.STATSPACK", line 71
    ORA-06512: at line 1
    Cause
    -- Its because of the bug # 2384758.
    "STATSPACK.SNAP GIVES ORA-1 ON STATS$LATCH_CHILDREN_PK WHEN I_SNAP_LEVEL=>10"
    -- The STATS$LATCH_CHILDREN table has a primary key constraint on (snap_id, dbid, instance_number, latch#, child#).
    Fix
    -- This is fixed in 9.0.2 and will not be backported to earlier versions because the level 10 is not a normal level to be setting unless requested by oracle support.

  • How to achieve parent - child record insert in forms

    Guys,
    I am new to forms. I do have a requirement where I need to create one tabular block for 10 rows (parent record) and then I need to create three tabular tabs of 5 rows for detailed records (child). That means each tab can have 5 records for 1 parent row.. Thats how this parent-child structure has ONE to MANY relationships
    To achieve this requirement I created one parent block of table type (using table XX_Parent) and then I created three detailed block for each tab (Tab_A,Tab_B,Tab_C) using child table (XX_Child). For each tab while inserting the data I took one context_value column in child table. i.e. when I insert the data using Tab_A , context_value column will be A. In the same way B and C for Tab_B for Tab_C respectively. And I wrote this logic at PRE-INSERT trigger for each tab. But when I insert the data for all the tabs, it allows me to enter successfully for Tab_A only, the moment I navigate from Tab_A to enter the data intoTab_B, it throws me error like "You are passing NULL value to set context_value". I hope I make the requirement clear to you.
    I am not sure if I am following the right approach to achieve my requirement. if its not right, please suggest me right one.. and if its right please guide me resolve the error..
    Looking forward to your reply.
    Thanks
    Sunil

    Andreas,
    I had already created relations between Matster Block -Tab_A block, Master Block -Tab_B block and Master Block - Tab_C block...
    The point is all the three tabs are created using one table XX_Child only.. I used context_value A,B and C respectively so that once I query the data for XX_Child from backend, I should be in a position to figure out what data is inserted using Tab A, B and C. why I need so .. because If take my entire form in query mode and search for a master record.. then Tab_A, tab_B and Tab_C display their respective data. I hope, I make you understand.. Can you please guide me.
    Thanks
    Sunil

  • TopLink inserts when it should update, unique constraint exception

    The title says most of it. I am creating a series of objects and then updating them in rapid succession. It would be great to handle all the values during the insert, but it's not possible for this process. The majority of the time, the cached object is updated correctly and no problem occurs, but every once in a while TopLink tries to re-insert the previously inserted object, instead of updating it. Obviously this throws a unique constraint exception for the PK, and boots me out of the process.
    I can refreshObject and then it works fine. I'm looking for the underlying cause though. I want to be able to use the cache!
    Thanks!!
    Aaron
    Oracle JDBC driver Version: 10.2.0.3.0
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    TopLink Release-Designation: 10g Release 3

    Hello,
    How are you obtaining these objects to update them? The likely cause is that you are running out of memory and the objects in the shared identity map are getting garbage collected due to weak references. This means that when they get registered, TopLink can't find them in the cache so assumes they are new (the default existence check is check cache).
    If this is the case, there are a few options.
    1) Increase the size of the cache for the class in question to something more appropriate for your application, or use a fullIdentyMap so nothing ever gets pushed out. Of course, a FullIdentityMap should not be used lightly as it prevents its objects from beign gc'd and has consequences to related objects as described in:
    Caching Causing Memory Leak Effect
    Both these options will require more memory resources though, so if garbage collection is running and clearing out the references because you are already low on memory, this might make GC need to run more frequently
    2) Increase the JVM memory. This assumes completely that GC is clearing out the unused weak references from your cache because it is low on memory - GC can still occur so it doesn't guarantee the problem will be any better
    3) Read in the object through the UnitofWork before making changes (instead of using RegisterObject on existing objects), use the registerExistingObject for known existing objects or use the uow mergeClone method. Merge should cause the object to be read from the database if it is not in the cache, but it depends on the existence options used
    Best Regards,
    Chris

  • OWB Update/Insert throwing unique constraint ..

    Hello Al,
    I am currently facing issue when it is supposed to update/Insert the records in OWB10gR2.
    Also there are no duplicates in the source data while doing this.
    Any help is appreceated.
    Thanks,
    Suresh
    Edited by: user8745316 on Jul 27, 2010 12:58 AM

    Hi Nawneet,
    Thanks for the reply.
    My issue is something like this , there were duplicates from the source and we deleted them but still it gives this error @ Unique constraint voilated errror.
    I also can understand that as we have same matching records by key columns from source and target which should ideally be doing the update and if non matching should be inserting which is not happening now.
    can you please suggest me the issue.
    Thanks for your help.
    Suresh

Maybe you are looking for

  • Using colors in ical

    Is it possible to use different colors for different events within a day on ical and/or between days. So far I've only been able to change a color and then it affects the entire calendar. I'd like to use different colors for different events. Thanks

  • Is it possible to use a secondary index in embedded persistent class

    Hi, I'm new to Berkely DB Java Edition and have just started playing with it. To express a relation between two entities Foo and Bar, I am trying with an assocation class FooBarAssociation that is not an entity but rather a @Persistent-annotated embe

  • Segmentation Fault in webdb/wdblsnr

    Please Help! I've installed WebDB into an Server and Oracle 8i in anouther server. Linux : 2.2.13 Webdb : 2.2 Oracle : 8i EE (8.1.5) I have added the appropriate 'webdb' alias in the tnsnames.ora file. I start the WebDB Listener which starts and run

  • Apps password error?

    You are running adrepctl.sh version 115.32 Cannot complete applications logon. You may have entered an invalid applications password, or there may have been a database connect error. starting Reports Server for DEV on port 7003. Cannot complete appli

  • MacBook built-in iSight camera off center

    Hi Folks, Is there any way to re-align the built in iSight camera on a MacBook? In order to be centered in the image, I have to turn my MacBook about 8 or 9 degrees to the left. If I am sitting directly in front of the camera, I am off-center. Any he