Disabling Foreign keys before Insert
DB version:10gR2
Is it a standard practice to disable Foreign keys when you have Huge INSERTs . Is there performance enhancement by deferring the Foreign key Check during Huge INSERTs?
Our client want to disable the FKs before a huge INSERT. They say they can manually rectify all issues related to Foreign key violation resulting from Disabling the FK.
What do you guys reckon?
It should hapen an enhancement performance by deferring the Foreign key Check during Huge INSERTs.
The same thing with triggers.
If you are sure that data that you want to insert is not inconsistent with the data on the DB, or that you manually rectify inconsistencies after the insert, then there is no problem by disabling Foreign key constraints/triggers.
Also there are gains of performance if you drop of the indices (if there's any) and recreate after the Huge INSERT.
Regards.
Similar Messages
-
Drop partition without disabling foreign key
Hi All,
I have parent and child table.
Parent table
create table parent_1
(id number,
create_date date,
constraint parent_1_pk001 PRIMARY KEY (id))
PARTITION BY RANGE (create_date)
INTERVAL (NUMTODSINTERVAL(1,'DAY'))
(PARTITION parent_1_part VALUES LESS THAN ('01-JAN-2010'));
Child Table
create table child_1
(id number,
create_date date,
constraint child_1_fk001 FOREIGN KEY (id)
REFERENCES parent_1 (id))
PARTITION BY RANGE (create_date)
INTERVAL (NUMTODSINTERVAL(1,'DAY'))
(PARTITION create_date_part VALUES LESS THAN ('01-JAN-2010'));
I am having problems dropping partition.
Parent_1
1 26-JUL-12
2 26-JUL-12
Child_1
1 26-JUL-12
alter table CHILD_1 drop partition SYS_P274;
table CHILD_1 altered.
ON DROPPING PARENT PARTITION
alter table parent_1 drop partition SYS_P273;
Error report:
SQL Error: ORA-02266: unique/primary keys in table referenced by enabled foreign keys
02266. 00000 - "unique/primary keys in table referenced by enabled foreign keys"
*Cause: An attempt was made to truncate a table with unique or
primary keys referenced by foreign keys enabled in another table.
Other operations not allowed are dropping/truncating a partition of a
partitioned table or an ALTER TABLE EXCHANGE PARTITION.
*Action: Before performing the above operations the table, disable the
foreign key constraints in other tables. You can see what
constraints are referencing a table by issuing the following
command:
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = "tabnam";
PLEASE CAN I KNOW IF THERE IS ANY WAY TO DROP PARENT PARTITION WITHOUT DISABLE/ENABLE FOREIGN CONSTRAINTS
ThanksSQL Error: ORA-02266: unique/primary keys in table referenced by enabled foreign keys
02266. 00000 - "unique/primary keys in table referenced by enabled foreign keys"
*Cause: An attempt was made to truncate a table with unique or
primary keys referenced by foreign keys enabled in another table.
Other operations not allowed are dropping/truncating a partition of a
partitioned table or an ALTER TABLE EXCHANGE PARTITION.
*Action: Before performing the above operations the table, disable the
foreign key constraints in other tables. You can't do that until you disable the foreign key constraint
http://jonathanlewis.wordpress.com/2006/12/10/drop-parent-partition/
Hope this helps
Mohamed Houri
www.hourim.wordpress.com -
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
Hi,
I am trying to delete data from a table by dropping a partition. I have identified all the child tables by running the following command.
select 'select count(*) from '||table_name||' where employee_id = 100;'
from dba_constraints
where constraint_type='R'
and r_constraint_name in
(select constraint_name from dba_constraints
where constraint_type in ('P','U') and table_name='EMPLOYEE);
'SELECTCOUNT(*)FROM'||TABLE_NAME||'WHEREEMPLOYEE_ID_ID=100;'
select count(*) from PT_ORDERS where employee_id = 100;
select count(*) from PT_DEP where employee_id = 100;
select count(*) from PT_SKILLSET where employee_id = 100;
I dropped the partition for employee_id 100 in all of the child tables. The select count(*) returns 0 rows for each of the above.
When I try to run the below command on the EMPLOYEE table, I get 'ORA-02266: unique/primary keys in table referenced by enabled foreign keys'.
alter table EMPLOYEE drop partition EMP_ID_100;
I cant see why I am unable to drop this partition now as there is now child data in any of the referenced tables. Any suggestions or help on this would be greatly appreciated.
Thanks.
Rgs,
RobYou should disable foreign key constraints first and drop partition. Deletion of rows or dropping partitions in childs don't work in this case
as you have the global dependency:
<PRE>
SQL> create table scott.t (x int primary key, y int)
2 partition by list (y) (
3 partition p_1 values(1), partition p_2 values(2))
4 /
Table created.
SQL> create table scott.t_c (x int references scott.t(x), y int)
2 partition by list (y) (
3 partition p_1 values(1), partition p_2 values(2))
4 /
Table created.
SQL> insert into scott.t values(1,1)
2 /
1 row created.
SQL> insert into scott.t values(2,2)
2 /
1 row created.
SQL> insert into scott.t_c values(1,1)
2 /
1 row created.
SQL> insert into scott.t_c values(2,2)
2 /
1 row created.
SQL> commit;
Commit complete.
SQL> alter table scott.t_c drop partition p_2;
Table altered.
SQL> alter table scott.t drop partition p_2;
alter table scott.t drop partition p_2
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
SQL> select constraint_name from dba_constraints
2 where owner = 'SCOTT' and constraint_type = 'P'
3 and table_name = 'T';
CONSTRAINT_NAME
SYS_C0011058
SQL> select constraint_name from dba_constraints
2 where owner = 'SCOTT' and constraint_type = 'R'
3 and r_constraint_name = 'SYS_C0011058';
CONSTRAINT_NAME
SYS_C0011059
SQL> alter table scott.t_c disable constraint SYS_C0011059;
Table altered.
SQL> alter table scott.t drop partition p_2;
Table altered.
SQL> alter table scott.t_c enable novalidate constraint SYS_C0011059;
Table altered.
</PRE>
I guess you should consider such option as Referencial partitioning (with some restrictions).
Best wishes,
Dmitry. -
ECC6.0 - Foreign Key in BSEG for new custom field
When I create a new custom field in NewGL, it is created in some tables like BSEG and others. In BSEG there is no flag in the field "Foreign Keys" (I inserted it when I set the field), while in the others tables I find the flag.
How can I solve it? I think that I have to mark the field directly in BSEG. Is it true?
Let me know
ThanksHi Srini,
As per note 32662 it seems you have followed all the steps, but might be that you didn't do in proper sequence.
The note states that:
"If a new access sequence and condition table was created before the communication structure was modified, it must be deleted again. Items 1 to 5 must be carried out in the specified sequence."
So I guess the key for you would be to delete the Condition table and access and create them again.
Regards,
Ganesh -
Foreign Key Relationship.
Hi,
I asked a question in the link below(which I solved).
https://social.msdn.microsoft.com/Forums/en-US/514a4f48-b1fa-4fe7-bc2b-4c252b34cf50/insertion-of-null-value?forum=vbgeneral
Here my question is that:
We make relation of foreign keys to enforce user for accurate data insertion, but sometime we do need null values to be passed to attribute that is used as
Foreign key. We studied and know that Foreign keys are meant to except null values, which it doesn't(In simple way. I mean when we select an attribute as foreign key and check it to except nulls, then it should.)
As I explained in the upper link how I solved the problem, if similar problems have to be solved like that then,
Why we define Foreign Key over there, i mean it could be done without defining the Foreign key?
If it is necessary in any meaning then why we Enforce Foreign
Key Constraint as No,
to except nulls from user?
What effects does Enforce Foreign Key Constraint as No
gives to Foreign Key Constraints?
Thnx in advance.
Habib Ur RehmanHello Habib,
I do not think what you are seeing is normal and without having the exact DDL it will be hard to comment.
I suspect, you may had "NOT NULL" constraint on the foreign key column. thats why it is not allowing NULLs.
By definition, Foreign Key maintains(enforces) referential integrity and does allows NULLs. So, you should be able to enter nulls without having to disable the foreign key enforcement.
by setting
Enforce Foreign Key Constraint to NO, you are effectively disabling the enforcement. you are invalidating the whole purpose of the constraint.
The purpose of having that option(disabling foreign key) is to fasten the data load process bypassing the check(extra work) to make sure the value exists in the primary key table when importing large amounts of data. But to maintain the referential
integrity you should have that enabled.
I am not sure without having the ddl, where you did wrong.PLEASE POST YOUR DDL and it should be clear where it went wrong for you. but i hope this script below should help you understand...
CREATE TABLE [dbo].[Make]([sid] [int] NULL unique,[sname] [varchar](50) NULL)
go
CREATE TABLE [dbo].[Make_FK]([sno] [int] NULL unique,[sname] [varchar](50) NULL,[sid] [int] NULL
CONSTRAINT FK_MAKE FOREIGN KEY (sid) REFERENCES dbo.make (SID))
insert into make(sid,sname)
values(1,'sam')
insert into dbo.Make_FK(sno,sname,sid)
values(100,'somename',null)
select * from Make
--sid is null. SID is the foreig n key referring to sid in MAKE table.
select * from Make_FK
Hope it Helps!! -
Foreign key errors in sql plus
Hello, im pretty new to sql and i am stuck on a project in my database management class and i was wondering if anyone can help us out. I don't know if it would be easier to send what i've done or just post the error so if anyone could help it will be appreciated.
This is one part of the sql
CREATE TABLE PREREQUISITE_T
(COURSECODE VARCHAR2(10)NOT NULL,
PREREQUISITECODE VARCHAR2(20),
PRIMARY KEY (COURSECODE),
PRIMARY KEY (PREREQUISITECODE),
FOREIGN KEY (COURSECODE) REFERENCES COURSE_T(COURSECODE),
FOREIGN KEY (PREREQUISITECODE));
INSERT INTO PREREQUISITE_T VALUES ('23131', '3213');
INSERT INTO PREREQUISITE_T VALUES ('23541', '4213');
INSERT INTO PREREQUISITE_T VALUES ('23251', '3413');
INSERT INTO PREREQUISITE_T VALUES ('56131', '3513');
INSERT INTO PREREQUISITE_T VALUES ('75431', '3613');
INSERT INTO PREREQUISITE_T VALUES ('45631', '3813');
INSERT INTO PREREQUISITE_T VALUES ('65461', '3913');
INSERT INTO PREREQUISITE_T VALUES ('45351', '5413');
the error i get is
ERROR at line 1:
ORA-02298: cannot validate (STUDENT.SYS_C003016) - parent keys not found
It works fine without the primary keys but when i put in foreign keys it is all messed up. If there a a tutorial or anyone could take a look at the rest of the code i can send it out. Any help is appreciated.probably u had given the column value not exists in the reference table.
see the example
create table tst(x number ,y number);
alter table tst add constraints pk_x primary key(x);
create table tst1(x number, y number);
alter table tst1 add constraints fk_x foreign key(x) references tst(x);
SQL> insert into tst values(&x,&y);
Enter value for x: 1
Enter value for y: 2
old 1: insert into tst values(&x,&y)
new 1: insert into tst values(1,2)
1 row created.
SQL> /
Enter value for x: 2
Enter value for y: 3
old 1: insert into tst values(&x,&y)
new 1: insert into tst values(2,3)
1 row created.
SQL> commit;
Commit complete.
SQL> insert into tst1 values(&x,&y);
Enter value for x: 2
Enter value for y: 1
old 1: insert into tst1 values(&x,&y)
new 1: insert into tst1 values(2,1)
1 row created.
SQL> /
Enter value for x: 5
Enter value for y: 6
old 1: insert into tst1 values(&x,&y)
new 1: insert into tst1 values(5,6)
insert into tst1 values(5,6)
ERROR at line 1:
ORA-02291: integrity constraint (SHFLDEV.FK_X) violated - parent key not found -
Disable all the foreign keys in a database
Hy, what sql to use to disable all the foreign keys in a database and how to enable all them again. Thanks
select * from dba_constraints where constraint_type = 'R' and status = 'ENABLED'
ALTER TABLE table_name
disable CONSTRAINT constraint_name;
ALTER TABLE table_name
enable CONSTRAINT constraint_name;
select
'ALTER TABLE ' || OWNER || '.' || table_name || ' enable CONSTRAINT ' || constraint_name || ';'
from dba_constraints where constraint_type = 'R' and status = 'ENABLED';
Execute and save result for enable before disable
select
'ALTER TABLE ' || OWNER || '.' || table_name || ' disable CONSTRAINT ' || constraint_name || ';'
from dba_constraints where constraint_type = 'R' and status = 'ENABLED';
Execute result for disable. -
How to insert value for composed foreign key?
My problem when I update or insert to table Ffclient which has link 1-1 with other table ClientLoan by composes primary key loanId and clienId (break table). I auto mapping by Jdeveloper 10g version 10.1.2. In FfClient table has two fields compose foreign key of ClientLoan as loanId and clienId not nullable. In toplink object Ffclient it only has one reference ClientLoan object by clientLoan field, not has two fields loanId and clienId . When I insert or update to database, I can't set value for these two fields direct so I have created new ClientLoan object and set value for composed primary key loanId and clienId, after that set it to object Ffclient. But when I update or insert to database it occurs exception about insert null for two not nullable fields: loanId and clienId.
Any one has error as mime? Any one help me correct my error.
Thanks in advance.
Mapping is:
â¦.
<database-mapping>
<attribute-name>ffclientCollection</attribute-name>
<read-only>false</read-only>
<get-method-name>getFfclientCollection</get-method-name>
<set-method-name>setFfclientCollection</set-method-name>
<reference-class>uk.co.lsb.elb.toplink.Ffclient</reference-class>
<relationship-partner-attribute-name>clientLoan</relationship-partner-attribute-name>
<is-private-owned>false</is-private-owned>
<uses-batch-reading>false</uses-batch-reading>
<indirection-policy>
<mapping-indirection-policy>
<type>oracle.toplink.internal.indirection.TransparentIndirectionPolicy</type>
</mapping-indirection-policy>
</indirection-policy>
<container-policy>
<mapping-container-policy>
<container-class>oracle.toplink.indirection.IndirectList</container-class>
<type>oracle.toplink.internal.queryframework.ListContainerPolicy</type>
</mapping-container-policy>
</container-policy>
<source-key-fields>
<field>LSB.CLIENT_LOAN.CLIENT_ID</field>
<field>LSB.CLIENT_LOAN.LOAN_ID</field>
</source-key-fields>
<target-foreign-key-fields>
<field>LSB.FFCLIENT.CLIENT_ID</field>
<field>LSB.FFCLIENT.LOAN_ID</field>
</target-foreign-key-fields>
<type>oracle.toplink.mappings.OneToManyMapping</type>
</database-mapping>
â¦..
<database-mapping>
<attribute-name>clientLoan</attribute-name>
<read-only>false</read-only>
<reference-class>uk.co.lsb.elb.toplink.ClientLoan</reference-class>
<relationship-partner-attribute-name>ffclientCollection</relationship-partner-attribute-name>
<is-private-owned>false</is-private-owned>
<uses-batch-reading>false</uses-batch-reading>
<indirection-policy>
<mapping-indirection-policy>
<type>oracle.toplink.internal.indirection.BasicIndirectionPolicy</type>
</mapping-indirection-policy>
</indirection-policy>
<uses-joining>false</uses-joining>
<foreign-key-fields>
<field>LSB.FFCLIENT.CLIENT_ID</field>
<field>LSB.FFCLIENT.LOAN_ID</field>
</foreign-key-fields>
<source-to-target-key-field-associations>
<association>
<association-key>LSB.FFCLIENT.LOAN_ID</association-key>
<association-value>LSB.CLIENT_LOAN.LOAN_ID</association-value>
</association>
<association>
<association-key>LSB.FFCLIENT.CLIENT_ID</association-key>
<association-value>LSB.CLIENT_LOAN.CLIENT_ID</association-value>
</association>
</source-to-target-key-field-associations>
<type>oracle.toplink.mappings.OneToOneMapping</type>
</database-mapping>Yes, many thanks for you reply.
My project has many layer (include DAO + EJB + BO + WEB).
Toplink objects which are auto created by TopLink has only using in DAO and EJB layer, then toplink objects are transfer to Bean objects (valueObject) which are contain primitive java type as int, long, double... not java wrapper object as Integer, Long, Double... Bean objects are using from EJB to WEB layer. So when set value to bean object from toplink object I sometime don't set all reference toplink object to reference object of bean (although bean has references bean object as toplink object) because there are too big. So when I update data from WEB layer to EJB layer, before update to database, I must get fill all data for foreign key of update object by create new reference toplink object, add reference_id to this object and set it to update object. I waste a lot of time, its very handwork and tire. Are you has any solution about this problem?
Thank in advanced.
ThangNQ -
How to insert data into two tables linke with foreign key..
I have two tables
1)EMP(emp_ID,username,emp_type_code)
emp_ID is primary key, emp_type_code is a foreign key references emptype table.
2)emptype(emp_type_code,emp_type_descripton)
emp_type_code is primary key
Could anyone help me ..how to insert data into EMP table. How to insert data into two tables linke with foreign key..CREATE TABLE "CATDB"."DWDIMUSER"
"USER_ID" NUMBER(10,0) NOT NULL ENABLE,
"SPECIALTY_ID" NUMBER(10,0),
"FULLNAME" VARCHAR2(20 BYTE),
"FNAME" VARCHAR2(20 BYTE),
"LNAME" VARCHAR2(20 BYTE),
"USER_SUBTYPE" VARCHAR2(20 BYTE),
CONSTRAINT "DIMUSER_PK" PRIMARY KEY ("USER_ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "CATDB" ENABLE,
CONSTRAINT "DIMUSER_DIMSPECIALTY_FK" FOREIGN KEY ("SPECIALTY_ID") REFERENCES "CATDB"."DWDIMSPECIALTY" ("SPECIALTY_ID") DISABLE
CREATE TABLE "CATDB"."DIMSPECIALTY"
"SPECIALTY_ID" NUMBER(10,0) NOT NULL ENABLE,
"SPECIALTY_NAME" VARCHAR2(100 BYTE),
CONSTRAINT "DIMSPECIALTY_PK" PRIMARY KEY ("SPECIALTY_ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "CATDB" ENABLE
INSERT INTO DIMUSER (FullName, FNAME, LNAME, USER_TYPE, USER_SUBTYPE)
SELECT DISTINCT
Engineer AS FullName,
regexp_substr(Engineer , '[^,| ]+', 1, 1) as FName,
regexp_substr(Engineer , '[^,| ]+', 1, 2) as LName ,
'Engineer'
FROM EMPLOYEELOOKUP;
INSERT INTO DIMSPECIALTY (SPECIALTY_NAME)
SELECT DISTINCT SPECIALITY
FROM EMPLOYEELOOKUP;
COMMIT;
CREATE TABLE employeelookup ...IS A TABLE THAT HAS ALL THE DATA NEDED TO BE FILLED IN BOTHE TABLES...
CREATE TABLE "CATDB"."EMPLOYEELOOKUP"
"EMPLOYEELOOKUP_ID" NUMBER(10,0) NOT NULL ENABLE,
"ENGINEER" VARCHAR2(25 BYTE),
"SPECIALTY" VARCHAR2(20 BYTE),
CONSTRAINT "DIMSPECIALTY_PK" PRIMARY KEY ("EMPLOYEELOOKUP_ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "CATDB" ENABLE
DATA IN EMPLOYEELOOKUP
Engineer, Specialty,
John, Dow, Electronis,
Dow, Jons, Technician
Stan Smithers Sales
Mark, Richards Marketing
Jenny, Lane Marketing
John, Lee Sales
I NEED TO LOAD THE FOREIGN KEY IN DIMUSER FROM THE DIMSPECIALTY TABLE?
BY USING THE LOOKUP TABLE TO MARCH THE NAMES UNDER THE Engineer COLUMN, SPECIALTY COLUMNE DISTICTIVLY BY JOINING THE DIMSPECILTY TO RISTIVE THE PRIMARY KEY AND FILL IT IN THE DIMUSER TABLE AS A FOREIGNE KEY. -
Before delete trigger and foreign key relationship
Hi,
I am analysing one database for migration. On one parent table there is before delete trigger , to delete records from child. Also there is foreign key relationship on child table for this parent table.
When I am deleting a row from parent, message gets displayed as "there are child records found."
I would like to know, if there is foreign key relatioship then delete trigger on parent does't work, what is exactly happening?Could you post that trigger code and the Oracle version as well?
With basic assumptions, I can't reproduce what you have stated here.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> create table parent (id number primary key);
Table created.
SQL> create table child (id number);
Table created.
SQL> alter table child add constraint fk_parent foreign key (id) references parent;
Table altered.
SQL> create or replace trigger bdr_parent
2 before delete on parent
3 for each row
4 begin
5 delete from child where id = :old.id;
6 end;
7 /
Trigger created.
SQL> insert into parent (id) values (1);
1 row created.
SQL> insert into child (id) values (1);
1 row created.
SQL> commit;
Commit complete.
SQL> delete from parent where id = 1;
1 row deleted.
SQL> select * from parent;
no rows selected
SQL> select * from child;
no rows selected
SQL> rollback;
Rollback complete.
SQL> alter table child drop constraint fk_parent;
Table altered.
SQL> alter table child add constraint fk_parent foreign key (id) references parent on delete cascade;
Table altered.
SQL> delete from parent where id = 1;
delete from parent where id = 1
ERROR at line 1:
ORA-04091: table SCOTT.CHILD is mutating, trigger/function may not see it
ORA-06512: at "SCOTT.BDR_PARENT", line 2
ORA-04088: error during execution of trigger 'SCOTT.BDR_PARENT'
SQL> -
Can not insert null into foreign key issue
Hi ,
I am having parent-child relationship table.
In the child table when I am adding a new record , data is getting inserted with foreign key.
After insert if I immediately update the same record. Its giving error that can not insert null into foreign key.
If i click on rollback button I am able to update that record properly.Hi ,
I am having parent-child relationship table.
In the child table when I am adding a new record , data is getting inserted with foreign key.
After insert if I immediately update the same record. Its giving error that can not insert null into foreign key.
If i click on rollback button I am able to update that record properly. -
In ADF how can i insert data in multiple table if they have foreign key
I have started working on ADF and can anybody inform me in ADF how can i insert data in multiple table if they have foreign key,please?
Thnak you very much.Hello,
Still no luck.I am surely doing silly mistakes.Anyway,Here are my workings-
1> student_mst (id(pk),studentname) and student_guard_mst(id(fk),guardianname)
2> created EO from both of the tables,made id in both EO as DBSequence and an association was also generated.
3> i made that association composite by clicking the checkbox
4> i created 2 VO from 2 EO.
5> put those VO in Application Module.
6> dragged and dropped 2 VO on my jspx page and dropped them as ADF Form.
Now what to do please? -
How to insert a new record to table with foreign key
I have 3 tables like this :
CREATE TABLE PERSON (
PK INTEGER NOT NULL,
NAME VARCHAR(10),
SSNUM INTEGER,
MGR INTEGER);
ALTER TABLE PERSON ADD CONSTRAINT PK_PERSON PRIMARY KEY (PK);
ALTER TABLE PERSON ADD CONSTRAINT FK_PERSON FOREIGN KEY (MGR) REFERENCES
PERSON (PK);
/* Tables
CREATE TABLE PROJECT (
PK INTEGER NOT NULL,
CODE_NAME INTEGER);
ALTER TABLE PROJECT ADD CONSTRAINT PK_PROJECT PRIMARY KEY (PK);
/* Tables
CREATE TABLE XREF (
PERSON INTEGER NOT NULL,
PROJECT INTEGER NOT NULL);
ALTER TABLE XREF ADD CONSTRAINT PK_XREF PRIMARY KEY (PERSON, PROJECT);
ALTER TABLE XREF ADD CONSTRAINT FK_XREF1 FOREIGN KEY (PERSON) REFERENCES
PERSON (PK);
ALTER TABLE XREF ADD CONSTRAINT FK_XREF2 FOREIGN KEY (PROJECT) REFERENCES
PROJECT (PK);
I do like the way of "ReverseTutoral" and the file .jdo here :
<?xml version="1.0" encoding="UTF-8"?>
<jdo>
<package name="reversetutorial">
<class name="Person" objectid-class="PersonId">
<extension vendor-name="kodo" key="class-column" value="none"/>
<extension vendor-name="kodo" key="lock-column" value="none"/>
<extension vendor-name="kodo" key="table" value="PERSON"/>
<field name="name">
<extension vendor-name="kodo" key="data-column"
value="NAME"/>
</field>
<field name="person">
<extension vendor-name="kodo" key="pk-data-column"
value="MGR"/>
</field>
<field name="persons">
<collection element-type="Person"/>
<extension vendor-name="kodo" key="inverse"
value="person"/>
<extension vendor-name="kodo" key="inverse-owner"
value="person"/>
</field>
<field name="pk" primary-key="true">
<extension vendor-name="kodo" key="data-column"
value="PK"/>
</field>
<field name="ssnum">
<extension vendor-name="kodo" key="data-column"
value="SSNUM"/>
</field>
<field name="xrefs">
<collection element-type="Xref"/>
<extension vendor-name="kodo" key="inverse"
value="person"/>
<extension vendor-name="kodo" key="inverse-owner"
value="person"/>
</field>
</class>
<class name="Project" objectid-class="ProjectId">
<extension vendor-name="kodo" key="class-column" value="none"/>
<extension vendor-name="kodo" key="lock-column" value="none"/>
<extension vendor-name="kodo" key="table" value="PROJECT"/>
<field name="codeName">
<extension vendor-name="kodo" key="data-column"
value="CODE_NAME"/>
</field>
<field name="pk" primary-key="true">
<extension vendor-name="kodo" key="data-column"
value="PK"/>
</field>
<field name="xrefs">
<collection element-type="Xref"/>
<extension vendor-name="kodo" key="inverse"
value="project"/>
<extension vendor-name="kodo" key="inverse-owner"
value="project"/>
</field>
</class>
<class name="Xref" objectid-class="XrefId">
<extension vendor-name="kodo" key="class-column" value="none"/>
<extension vendor-name="kodo" key="lock-column" value="none"/>
<extension vendor-name="kodo" key="table" value="XREF"/>
<field name="person">
<extension vendor-name="kodo" key="pk-data-column"
value="PERSON"/>
</field>
<field name="person2" primary-key="true">
<extension vendor-name="kodo" key="data-column"
value="PERSON"/>
</field>
<field name="project">
<extension vendor-name="kodo" key="pk-data-column"
value="PROJECT"/>
</field>
<field name="project2" primary-key="true">
<extension vendor-name="kodo" key="data-column"
value="PROJECT"/>
</field>
</class>
</package>
</jdo>
Data of those tables are :
PERSON :
| PK | NAME | SSNUM | MGR |
| 1 | ABC | 1 | 1 |
| 2 | DEF | 5 | 1 |
PROJECT
| PK | CODE_NAME |
| 1 | 12 |
| 2 | 13 |
And now I want to add a new record into table XREF : insert into XREF
values (1,1);
public void createData() {
Xref xref = new Xref();
Person person = new Person(1);
Project project = new Project(1);
xref.setPerson(person);
xref.setProject(project);
person.getXrefs().add(xref);
person.getXrefs().add(xref);
pm.currentTransaction().begin();
pm.makePersistent(xref);
pm.currentTransaction().commit();
I don't know why Kodo automatically insert new record to table PERSON ->
confilct Primary Key. The errors are :
0 [main] INFO kodo.Runtime - Starting Kodo JDO version 2.4.1
(kodojdo-2.4.1-20030126-1556) with capabilities: [Enterprise Edition
Features, Standard Edition Features, Lite Edition Features, Evaluation
License, Query Extensions, Datacache Plug-in, Statement Batching, Global
Transactions, Developer Tools, Custom Database Dictionaries, Enterprise
Databases, Custom ClassMappings, Custom ResultObjectProviders]
41 [main] WARN kodo.Runtime - WARNING: Kodo JDO Evaluation expires in 29
days. Please contact [email protected] for information on extending
your evaluation period or purchasing a license.
1627 [main] INFO kodo.MetaData -
com.solarmetric.kodo.meta.JDOMetaDataParser@e28b9: parsing source:
file:/D:/AN/Test/classes/reversetutorial/reversetutorial.jdo
3092 [main] INFO jdbc.JDBC - [ C:23387093; T:19356985; D:10268916 ] open:
jdbc:firebirdsql:localhost/3050:D:/An/test/temp.gdb (sysdba)
3325 [main] INFO jdbc.JDBC - [ C:23387093; T:19356985; D:10268916 ]
close:
com.solarmetric.datasource.PoolConnection@164dbd5[[requests=0;size=0;max=70;hits=0;created=0;redundant=0;overflow=0;new=0;leaked=0;unavailable=0]]
3335 [main] INFO jdbc.JDBC - [ C:23387093; T:19356985; D:10268916 ] close
connection
3648 [main] INFO jdbc.JDBC - Using dictionary class
"com.solarmetric.kodo.impl.jdbc.schema.dict.InterbaseDictionary" to
connect to "Firebird" (version "__WI-V6.2.972 Firebird 1.0.3)WI-V6.2.972
Firebird 1.0.3/tcp (annm)/P10") with JDBC driver "firebirdsql jca/jdbc
resource adapter" (version "0.1")
4032 [main] INFO jdbc.JDBC - [ C:25657668; T:19356985; D:10268916 ] open:
jdbc:firebirdsql:localhost/3050:D:/An/test/temp.gdb (sysdba)
4143 [main] INFO jdbc.SQL - [ C:25657668; T:19356985; D:10268916 ]
preparing statement <3098834>: INSERT INTO XREF(PERSON, PROJECT) VALUES
4224 [main] INFO jdbc.SQL - [ C:25657668; T:19356985; D:10268916 ]
executing statement <3098834>: [reused=1;params={(int)1,(int)1}]
4244 [main] INFO jdbc.SQL - [ C:25657668; T:19356985; D:10268916 ]
preparing statement <9090824>: INSERT INTO PERSON(MGR, NAME, PK, SSNUM)
VALUES (?, ?, ?, ?)
4315 [main] INFO jdbc.SQL - [ C:25657668; T:19356985; D:10268916 ]
executing statement <9090824>: [reused=1;params={null,null,(int)1,(int)0}]
4598 [main] WARN jdbc.JDBC - java.sql.SQLWarning: java.sql.SQLWarning:
resultSetType or resultSetConcurrency changed
4598 [main] WARN jdbc.JDBC - java.sql.SQLWarning: java.sql.SQLWarning:
resultSetType or resultSetConcurrency changed
4598 [main] INFO jdbc.JDBC - [ C:25657668; T:19356985; D:10268916 ] begin
rollback
4608 [main] INFO jdbc.JDBC - [ C:25657668; T:19356985; D:10268916 ] end
rollback 10ms
4628 [main] INFO jdbc.JDBC - [ C:25657668; T:19356985; D:10268916 ]
close:
com.solarmetric.datasource.PoolConnection@1878144[[requests=2;size=2;max=70;hits=0;created=2;redundant=0;overflow=0;new=2;leaked=0;unavailable=0]]
4628 [main] INFO jdbc.JDBC - [ C:25657668; T:19356985; D:10268916 ] close
connection
javax.jdo.JDOFatalDataStoreException:
com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper:
[SQL=INSERT INTO PERSON(MGR, NAME, PK, SSNUM) VALUES (null, null, 1, 0)]
[PRE=INSERT INTO PERSON(MGR, NAME, PK, SSNUM) VALUES (?, ?, ?, ?)]
GDS Exception. violation of PRIMARY or UNIQUE KEY constraint "PK_PERSON"
on table "PERSON" [code=335544665;state=null]
NestedThrowables:
com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper:
[SQL=INSERT INTO PERSON(MGR, NAME, PK, SSNUM) VALUES (null, null, 1, 0)]
[PRE=INSERT INTO PERSON(MGR, NAME, PK, SSNUM) VALUES (?, ?, ?, ?)]
GDS Exception. violation of PRIMARY or UNIQUE KEY constraint "PK_PERSON"
on table "PERSON"
at
com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwFatal(SQLExceptions.java:17)
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManager.java:416)
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:575)
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManagerImpl.java:438)
at reversetutorial.Finder.createData(Finder.java:74)
at reversetutorial.Finder.main(Finder.java:141)
NestedThrowablesStackTrace:
org.firebirdsql.jdbc.FBSQLException: GDS Exception. violation of PRIMARY
or UNIQUE KEY constraint "PK_PERSON" on table "PERSON"
at
org.firebirdsql.jdbc.FBPreparedStatement.internalExecute(FBPreparedStatement.java:425)
at
org.firebirdsql.jdbc.FBPreparedStatement.executeUpdate(FBPreparedStatement.java:136)
at
com.solarmetric.datasource.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:111)
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatementNonBatch(SQLExecutionManagerImpl.java:542)
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatement(SQLExecutionManagerImpl.java:511
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executeInternal(SQLExecutionManagerImpl.java:405)
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.flush(SQLExecutionManagerImpl.java:272
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManager.java:411)
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:575)
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManagerImpl.java:438)
at reversetutorial.Finder.createData(Finder.java:74)
at reversetutorial.Finder.main(Finder.java:141)
at org.firebirdsql.gds.GDSException: violation of PRIMARY or UNIQUE KEY
constraint "PK_PERSON" on table "PERSON
at org.firebirdsql.jgds.GDS_Impl.readStatusVector(GDS_Impl.java:1683)
at org.firebirdsql.jgds.GDS_Impl.receiveResponse(GDS_Impl.java:1636)
at org.firebirdsql.jgds.GDS_Impl.isc_dsql_execute2(GDS_Impl.java:865)
at
org.firebirdsql.jca.FBManagedConnection.executeStatement(FBManagedConnection.java:782)
at
org.firebirdsql.jdbc.FBConnection.executeStatement(FBConnection.java:1072)
at
org.firebirdsql.jdbc.FBPreparedStatement.internalExecute(FBPreparedStatement.java:420)
at
org.firebirdsql.jdbc.FBPreparedStatement.executeUpdate(FBPreparedStatement.java:136)
at
com.solarmetric.datasource.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:111)
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatementNonBatch(SQLExecutionManagerImpl.java:542)
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatement(SQLExecutionManagerImpl.java:511)
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executeInternal(SQLExecutionManagerImpl.java:405)
at
com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.flush(SQLExecutionManagerImpl.java:272)
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManager.java:411)
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:575)
at
com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManagerImpl.java:438)
at reversetutorial.Finder.createData(Finder.java:74)
at reversetutorial.Finder.main(Finder.java:141)
Exception in thread "main"First off, use the '-primaryKeyOnJoin true' flag when running the reverse
mapping tool so that you can get rid of that useless Xref class and have
a direct relation between Person and Project. See the documentation on
reverse mapping tool options here:
http://www.solarmetric.com/Software/Documentation/latest/docs/ref_guide_pc_reverse.html
But your real problem is that you are creating new objects, assigning
primary key values, and expecting them to represent existing objects.
That's not the way JDO works. If you want to set relations to existing
objects in JDO, you use the PM to look up those objects. If you try to
create new objects, JDO will assume you want to insert new records into
the DB, and you'll get PK conflicts like you see here.
There are several good books out on JDO; if you're just starting out with
it, they might save you a lot of time and help you master JDO quickly. -
How to insert record in child table with foreign key
Hi,
I am using Jdeveloper 11.1.2.0. I have two master table one child table.
How to insert and update a record in child table with foreign key ?
I have created VO based on three EO(one eo is updatable other two eo are references) by using joined query.
Thanks in Advance
Edited by: 890233 on Dec 24, 2011 10:40 PM... And here is the example to insert using sequenceimpl by getting the primary key of the master record and insert master and detail together.
Re: Unable to insert a new row with a sequence generated column id
-Arun -
Problem to insert id into the foreign key php/mysql
Hello all,
I'm having rouble to understand the process and there is no tutorial about my problem anywhere
I have two table:
Table 1 (member) with id, name, phone etc
Table2 (post) add_id, title, description, price, member_id
I got a form to post the add and I need to insert the id of table 1 into my table 2 member_id zone
Fisrt I did the recorset to get user id
$colname_rsMember = "-1";
if (isset($_SESSION['MM_Username'])) {
$colname_rsMember = $_SESSION['MM_Username'];
mysql_select_db($database_connect, $connect);
$query_rsMember = sprintf("SELECT * FROM member WHERE username='".$_SESSION['MM_Username']."'")or die(mysql_error());
$rsMember = mysql_query($query_rsMember, $connect) or die(mysql_error());
$row_rsMember = mysql_fetch_assoc($rsMember);
$totalRows_rsMember = mysql_num_rows($rsMember);
This part is working and I'm able to retreive info via echo just for testing
After this code I have my insert code
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form2")) {
$insertSQL = sprintf("INSERT INTO add (title, `description`, price, member_id) VALUES (%s, %s, %s, %s)",
GetSQLValueString($_POST['title'], "text"),
GetSQLValueString($_POST['description'], "text"),
GetSQLValueString($_POST['price'], "text"),
GetSQLValueString($_POST['member_id'], "int"));
mysql_select_db($database_connect, $connect);
$Result1 = mysql_query($insertSQL, $connect) or die(mysql_error());
$insertGoTo = "ok.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
header(sprintf("Location: %s", $insertGoTo));
Do I need to include hidden field in y form?
I'm having the same error message. Col member_id can't not be null
Any idea what I'm doing wrong?
Thank You!When someone logs in, Dreamweaver creates a session variable called $_SESSION['MM_Username']. Use that session variable to create a recordset to get the user's ID, which can then be entered into the foreign key field of the child table.
Dreamweaver automatically puts the code for recordsets immediately above the DOCTYPE declaration, so you will need to move it above the code for the Insert Record server behavior. So, it needs to be in this order:
Recordset to get user ID
Insert Record for child table
Maybe you are looking for
-
In What Package Are the style and diction Programs? [SOLVED]
I know this is an incredibly stupid question, but I cannot find what package I need for the style and diction programs... thank you for any information! Last edited by egan (2009-08-28 13:58:58)
-
Printing Turkish Characters in SAP Script
Hi I want to print a Form where I need to Print Turkish characters from Database. Its Print Preview is coming absolutely right but there is some problem while printing. I shows # symbol in places of Turkish Characters. I have checked the printer and
-
Hi experts, how can i save a Purchase Order (PO) pdf formate with po number Exampl :- po number is 4500000661. but when i am saving as a PDF formate in my system C drive its giving me a name of the file automaticalley E9A9F3F1A0970026B958F18D.pdf l
-
Correcting for white balance in high-ISO images
I just started using a Whibal card, and have a number of high ISO images that I'm having a hard time correcting in Aperture. Because of the grain, the white balance varies widely as I move my dropper across the card. Whether I use a white balance ref
-
Garage Band 3.05 and Leopard 10.5.2
I bought Leopard's family pack and recently started by installing Leopard on my Imac 24". Now Garage Band does not work anymore. I waited and waited and it does not work at all... When I try to start it, by itself or through a saved file, it does han