Finding foreign keys
hi,
anyone got sql that would tell which tables reference a primary key in a another table e.g. the link from primary key to foreign key in a schema?
thanks
query DBA_CONSTRAINTS
SQL> desc dba_constraints
Name Null? Type
OWNER NOT NULL VARCHAR2(30)
CONSTRAINT_NAME NOT NULL VARCHAR2(30)
CONSTRAINT_TYPE VARCHAR2(1)
TABLE_NAME NOT NULL VARCHAR2(30)
SEARCH_CONDITION LONG
R_OWNER VARCHAR2(30)
R_CONSTRAINT_NAME VARCHAR2(30)
DELETE_RULE VARCHAR2(9)
STATUS VARCHAR2(8)
DEFERRABLE VARCHAR2(14)
DEFERRED VARCHAR2(9)
VALIDATED VARCHAR2(13)
GENERATED VARCHAR2(14)
BAD VARCHAR2(3)
RELY VARCHAR2(4)
LAST_CHANGE DATE
INDEX_OWNER VARCHAR2(30)
INDEX_NAME VARCHAR2(30)
INVALID VARCHAR2(7)
VIEW_RELATED VARCHAR2(14)
Similar Messages
-
How to find foreign key in pl/sql
Error starting at line 1 in command:
DELETE FROM ZKET_SOLE WHERE IID_SOLA = 1
Error report:
SQL Error: ORA-02292: integrity constraint (IRCKIS.ZKETSTIP_ZKET_FK) violated - child record found
02292. 00000 - "integrity constraint (%s.%s) violated - child record found"
*Cause: attempted to delete a parent key value that had a foreign
dependency.
*Action: delete dependencies first then parent or disable constraint.
i need to find foreign key but i do not know how. I know that it must be in dictionary but i can not find it. I do not have access to ER model.
ThxYou could use a query similar to this:
SELECT ucc.constraint_name,ucc.table_name,ucc.column_name
FROM user_cons_columns ucc
JOIN user_constraints uc on uc.constraint_name=ucc.constraint_name
WHERE CONSTRAINT_TYPE='R'You could also use the ALL_CONSTRAINTS / ALL_CONS_COLUMNS views.
Hope this helps! -
Find foreign key which are able or not
Same as the topic ~ how can I find all the able/unable foreign key/contraints inside a database ? Using TSQL
Hello,
Please try the scripts provided on the following resources:
http://blog.sqlauthority.com/2009/07/17/sql-server-two-methods-to-retrieve-list-of-primary-keys-and-foreign-keys-of-database/
http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/
http://blog.sqlauthority.com/2007/09/16/sql-server-2005-list-all-the-constraint-of-database-find-primary-key-and-foreign-key-constraint-in-database/
Hope this helps.
Regards,
Alberto Morillo
SQLCoffee.com -
Hi,
i want to have the details like reference tablename,reference volumn name of foreign key for a particular table.
SELECT a.column_name,
c_pk.table_name r_table_name, c_pk.constraint_name r_pk
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
AND c.r_constraint_name = c_pk.constraint_name
WHERE c.constraint_type = 'R'
AND a.table_name = :TableNameUsing this query I am getting everything except the reference column name.
Can somebody please help?
ThanxYou need to add another join to ALL_CONS_COLUMNS:
SELECT a.column_name,
c_pk.table_name r_table_name, c_pk.constraint_name r_pk,
c_pk_c.column_name
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
AND c.r_constraint_name = c_pk.constraint_name
JOIN all_cons_columns c_pk_c ON c_pk_c.owner = c_pk.owner
AND c_pk_c.constraint_name = c_pk.constraint_name
WHERE c.constraint_type = 'R'
AND a.table_name = :TableName -
Finding foreign keys of a child table,grandchild and all dependendents
Hi All,
I just came up with this sceanrio
I have to delete a record in a parent table with a condition provided will have to find all the child tables depends on it and should recursively find all the dependents of the child table.
How to achieve this.Please help with a query or guide.Thanks in advanceThanks visakh it gave me an idea and this script helped me
DECLARE @mytable VARCHAR(30) SET @mytable = 'test'
DECLARE @RecordID VARCHAR(8)
SET @RecordID = '00000001'
DECLARE @Order INT SET @Order = 0
DECLARE @Count INT
declare @tblname varchar(100),@query NVARCHAR(max)
if OBJECT_ID('tempdb..#OrderList','U') is not null
DROP TABLE #OrderList
CREATE TABLE #TEMP
OrderNo INT,
TableName VARCHAR(50)
CREATE TABLE #OrderList
RecordNo INT,
OrderNo INT,
TableName VARCHAR(50)
INSERT INTO #TEMP
VALUES ( @Order,
@mytable )
WHILE ( EXISTS(SELECT TableName
FROM #TEMP
WHERE OrderNo = @Order) )
BEGIN
SET @Order= @Order + 1;
INSERT INTO #TEMP
SELECT @Order,
t1.TABLE_NAME AS PointsFrom
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS r
JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS t1
ON t1.CONSTRAINT_NAME = r.CONSTRAINT_NAME
JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS t2
ON t2.CONSTRAINT_NAME = r.UNIQUE_CONSTRAINT_NAME
WHERE t2.table_name IN (SELECT TableName
FROM #TEMP
WHERE OrderNo = ( @Order - 1 ))
END
INSERT INTO #OrderList
SELECT Row_number() OVER (ORDER BY OrderNo, TableName),
#TEMP.OrderNo,
#TEMP.TableName
FROM #TEMP
DROP TABLE #TEMP
--SELECT * FROM #OrderList
SET @Count = (SELECT Max(RecordNo)
FROM #OrderList)
WHILE (@Count <> 0 )
BEGIN
select @tblname = TableName FROM #OrderList WHERE RecordNo = @Count
select @query = 'DELETE from '+ @tblname
select @query
exec sp_executesql @query
SET @Count = @Count-1
END -
Hi All,
Let's picture that I have a GW service called Search Helps and within that service I have a PersonalAreas Entity Set which acts as a search help for drop down fields effectively that need to select a Personal Area. I have 3 properties, with Personal Area Id and Company Code being the keys, and the text for Personal Area being the 3rd and last property. You really need to filter PersonalAreas by Company Code otherwise it's a fairly useless result set.
Now within a different GW service, I have an entity called Position which has a single key of PositionId. There is also a a property of company code on this Position.
Now rather than asking the UI developer to get the Company code value and filter PersonalAreas with it directly, I thought it would be nicer for the UI developer just to use the navigation from a specific Position to PossiblePersonalAreas. e.g. Positions('123')/PossiblePersonalAreas returns the entity set of PersonalAreas filtered by the Position's Company Code.
So with that in mind, I add the external model reference pointing at the search helps service; then create an external association via the sneaky External Associations Editor button (that doesn't appear on the Wizard just to confuse you), and set up my Dependent entity to point at the Search Helps PersonalAreas entity.
At this point I really want to tie the Position's Company Code to the PersonalAreas Company Code, but all I can do is set up a referential constraint of PositionId to CompanyCode or have no referential constraint at all (note - in my example I added the referential constraint as there is an issue with navigation keys being provided to external associations from what I can tell - more about this below).
So, without any other option, I go into my GetEntitySet method of PersonalAreas and write something like the following:
CASE iv_source_name.
WHEN 'Position'.
READ TABLE it_filter_select_options ASSIGNING <filter> INDEX 1.
CHECK sy-subrc = 0.
READ TABLE <filter>-select_options assigning <select_option> INDEX 1.
CHECK sy-subrc = 0.
position_id = <select_option>-low.
* Get company code for position
TRY.
CREATE OBJECT o_position
EXPORTING
i_position_id = position_id.
o_position->get_cost_centre_information(
IMPORTING
e_company_code = company_code
CATCH zcx_hr_object.
ENDTRY.
endcase.
* Continue with retrieving PersonalAreas for given Company Code
<Remaining code not shown>
e.g. I have to assume CompanyCode is actually "Position Id" when the source of this call is from Position (I could also look at the navigation to find this has come from Position but if you're wondering, unfortunately for external associations, the key is not included in this for some reason but the same followup logic of reloading the object would be required).
So the question I'm hoping the answer to is Yes is: Am I missing something in my understanding here?
Thanks,
Matt
Edit since posting and playing around a bit more: Thinking about this further - it's unfortunate, but the navigation property in odata really implies the dependent entity has knowledge of the principal entity and realistically must know how to instantiate it if it needs to get data based on one of the properties.
Now while I'm fine with that (sort of) I think it's wrong that the dependent entity needs to have the required key properties to hold the principal entities as it makes something like a generic search help impossible to do with navigation - Maybe I just need to be done with that and expect filters to be used by UI programmers to find foreign key'ed entities....Hi Matt,
I'm not surprised that you have an issue with this. One bugbear I have with Gateway is that for some reason the designers don't think any context beyond the immediate preceding navigation node is important. They don't support this within the same service,so it's hardly likley to work in a service reference.
I may be wrong but I don't think GW is OData compliant in this respect. If I have the navigation path /blindservice/FromHereSet(1)/ToAPoints(22)/ToBPoints, it's rather restrictive to say I cannot see the initial key of '1' in the path when I am trying to resolve 'ToBPoints'. If that value - where I started - is key to the context, I have to know it.
Currently the only way to access this context is to embed the 'key history' in the intermediate entities, i.e. /blindservice/FromHereSet(1)/ToAPoints(1,22)/ToBPoints. In my view that is corrupting the URl to suit the limitations of the SAP OData implementation. What's even more confusing/frustrating is that the technical request context appears to be able to store the stacked navigation keys but doesn't make use of this design.
I feel your pain
Ron. -
Find which tables are linked to this one via foreign keys
Hi, I need to drop & recreate a table, but this table is referenced by other tables via foreign key constraints.
1. Is there a query I can run to find those tables (the ones referencing this one) ?
2. What is the standard way to drop & recreate this table being referenced by others?1) You can try the following query:
select r.owner, r.table_name
from user_constraints r, user_constraints o
where r.r_owner = o.owner and r.r_constraint_name = o.constraint_name
and o.constraint_type in ('P','U') and r.constraint_type = 'R'
and o.table_name = 'DEPT'
2) To drop tables with references you can also use drop table cascade constraints,
which will also drop constraints from tables:
[email protected]> drop table dept;
drop table dept
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys
[email protected]> drop table dept cascade constraints;
Table dropped.
Another way is to prepare a script which will remove the tables in proper order.
Best Regards
Krystian Zieja / mob -
Binding for table produces list for other tables using foreign key and crea
Using
software Jdev 11G, WLS 11G, Oracle DB 11G, Windows Vista platform
technology EJB 3.0, jspx, backing beans, session bean
I cannot create a namedquery on my secondary table. The method for the column uses the entity object rather than the name and value of the column.
For instance,
(Coketruck) table has inventory records(Products) table
Coketruck has one to many to the Products table
Products has a many to one to the Coketruck
I need to return the products from the product table based on the CokeTruck but I cannot create a namedQuery because the method in the Product table is an entity object type instead of a long that I can use to look up all the products based off the column truck_id.
This is what I was expecting…
Private Long truckId;
public Long getTruckId() {
return truckId;
public void setTruckId (Long truckId) {
this. truckId = truckId;
Instead this is what I have…
@ManyToOne
@JoinColumn(name = "TRUCK_ID")
private Coketruck coketruck;
this. coketruck = coketruck
public Coketruck getCoketruck() {
return coketruck;
public void set Coketruck (Coketruck coketruck) {
this. coketruck = coketruck;
How do I do a query on the Product table to return all the products that are in the coketruck?
If I do the following it expects for me to pass the Entity Object which I cannot use as search criteria for my find method.
@NamedQuery(name = "Products.findById", query = "select o from Products o where o.truckId = :truckId")
On a different note but the same song…
I noticed that when I look at my Session Bean Data Contols that the coketruck already has a list of the products. I have created a jsp page with a backing bean and have been able to use the namedquery on the coketruck entity to retrieve the productList. Unfortunately I need to sort the products by type and was also not able to find where to perform the work to be able to iterate through the productList to get my desired display. Therefore I started looking at doing another namedquery that would only retrieve the product_type ordering by the truckId.
Seems I have come full circle… I don’t care what method I have to use to get the info back.
Any help is greatly appreciated!user9005175 wrote:
Hi!
I work on an application wich uses a shopping cart stored in a database. The shopping cart uses two tables:
CART: Holds information common for one shopping cart: the user it is connected to etc.
- Primary key: CART_ID
CART_ROW: One row in the cart, e.g. one new product to buy.
- Primary key: ROW_ID
- Foreign key: CART_ROW.CART_ID references CART.CART_ID
From the code the rows in the cart are collected per cart, as is modelled by the foreign key. There exists one more relationship, which we use in the code, but which is not modelled by a foreign key in the database. One row can be dependent on another row, which makes the other row a parent.
CART_ROW has a column PARENT_ID which references CART_ROW.ROW_ID.
Should we add a foreign key for PARENT_ID? Or are there any questions to consider when it is a foreign key to the same table?
I suggest to add foreign key it wont harm the performance (except while on insert when there would be validation for the foreign key). But it would prevent users to insert wrong/corrupt data either through code or directly by loggin in the database.
A while ago we added indexes, both on ROW_ID and on PARENT_ID. Could the index on PARENT_ID have been harmful, since there is no foreign key?
Index on parent_id would only be harmful if you do not make use of index after creating it (i.e. there is no query which make use of this index).
And if you decide to have a foreign key on parent_id then I suggest to have index too on parent_id as it would be helpful atleast when you delete any record in this table.
Best regards! -
Can we associate index with foreign key?
hello
i have searched and could not find the answer to the above;
i have a foreign key constraint on the tables; i added an index on that column as well;
however when i query the all_constraints, under index_name for this foreign constraint there is nothing; only when i have PK/UK i case see indexes associated with them;
will then oracle still associate my index with the FK constrained column? or i need to excplicity associate it with the foreign key column? if so, how to do that?
thx
rgdsHi,
UserMB wrote:
i have a foreign key constraint on the tables; i added an index on that column as well;It helps if you give a specific example, such as:
"I have a foreign key constraint, where emp.deptno references dept.deptno. (Deptno is the primary key of dept.) I created an index called emp_deptno_idx on emp.deptno as well."
however when i query the all_constraints, under index_name for this foreign constraint there is nothing; only when i have PK/UK i case see indexes associated with them;Not all indexes are associated with a constraint. In the example above, you wouldn't expect to see anything about the index emp_demptno_idx in all_constraints or in all_cons_columns.
will then oracle still associate my index with the FK constrained column? or i need to excplicity associate it with the foreign key column? if so, how to do that?In the situation above, Oracle will still use the index when the optimizer thinks it will help. You don't have to do anything else. -
Subquery in IF statement in trigger, without using foreign keys
Hello,
I'm investigating ways of writing a subquery in an IF statement, which is placed inside a trigger.
I wanna write smth like IF (:new.jazz not in (select goldies from T where ... )) etc. I don't know whether the fact that the IF is in a trigger adds some additional restrictions. (Does it?)
So far I found the solution described here: SubQuery Comparison in If Statement which I find a bit tacky, I could have the 'cooleststarinthegalaxy' instead of 1 and seems you need to do extra light, but still extra lifting.
I also read about the possibility of using MERGE, which I'm currently researching.
Is there any other way?
Thanks
Edited by: BluShadow on 14-Nov-2012 13:37
fixed link
Edite by me: the question is how (if possible) to do this without a foreign key.
Edited by: questioningq12 on Nov 14, 2012 6:11 AM
Edited by: questioningq12 on Nov 14, 2012 6:13 AMHi,
questioningq12 wrote:
Say I have tables A(namea varchar(10)), B(nameb varchar(10)), and B contains tuples ('1stname','2ndname').
I wrote a trigger before insertion, for each row, on table A. For a tuple t to be inserted, it should check whether t.namea is in the set of values nameb from B.
E.g., INSERT INTO A VALUES('1stname') should work. But INSERT INTO A VALUES ('3rdname') should fail. You can use a foreign key constraint for that.
If the tables already exist, and b.nameb is declared as UNIQUE (or PRIMARY KEY), then you can say:
ALTER TABLE a
ADD CONSTRAINT a_namea_fk
FOREIGN KEY (namea)
REFERENCES b (nameb)
;If you had a situation where you really needed to query a table in PL/SQL, and you weren't sure if the query would find anything, you could put the query in its own BEGIN ... EXCEPTION block, and test for NO_DATA_FOUND.
If you're just checking to see if a row exists or not, you can always write a query that is guaranteed to return exactly 1 row, like this:
BEGIN
SELECT COUNT (*)
INTO x
FROM b
WHERE nameb = :NEW.namea
AND ROWNUM = 1;
IF x = 0
THEN
... -- print msgs, raise exceptions etc
END IF;
END;Edited by: Frank Kulash on Nov 14, 2012 9:22 AM
Added example -
How can I have multiple instances of a column that itself holds a foreign key reference?
I am new to Visual Studio so to start learning it I first of all downloaded a sample available at https://code.msdn.microsoft.com/ADPNET-Entity-Framework-2d1160cb and started working around it. Since I have fairly good knowledge of VB6 and SQL it did
not take much time for me to understand the whole pattern the sample is based on. Had Microsoft given a detail explanation or a walk through of the sample it would have been much easier to understand the basics. However, I somehow managed to work around it
and have build a small desktop application in wpf using Entity Framework and MVVM. But a point has come where I have got completely stuck up finding no way out. The problem is as under:
I have two tables. 1 Advocate and 2 Party. Table Advocate would contain names of advocates and would have a primary key. Similarly Party would have names and their respective primary keys.
Then I have another two tables 1. Case and 2 CaseDetail. Table Case would simply hold three columns: 1. CaseId 2. CaseNo and 3. Year. Table CaseDetail would have CaseDetailId as a primary key the CaseId as a Foreign Key. Now what I need is that a particular
case could have multiple advocates and multiple petitioners. So the table CaseDetail would have two columns to hold advocateId and PartyId as a Foreign Keys.
If you look at the sample referred above you would not find how to deal with such a case. When I follow the pattern of the sample I get host of design time and runtime errors.
Therefore, please suggest what strategy should be adopted in a scenario described above while developing WPF application using Entity Framework and MVVM.I am new to Visual Studio so to start learning it I first of all downloaded a sample available at https://code.msdn.microsoft.com/ADPNET-Entity-Framework-2d1160cb and started working around it. Since I have fairly good knowledge of VB6 and SQL it did not
take much time for me to understand the whole pattern the sample is based on. Had Microsoft given a detail explanation or a walk through of the sample it would have been much easier to understand the basics. However, I somehow managed to work around it and
have build a small desktop application in wpf using Entity Framework and MVVM. But a point has come where I have got completely stuck up finding no way out. The problem is as under:
I have two tables. 1 Advocate and 2 Party. Table Advocate would contain names of advocates and would have a primary key. Similarly Party would have names and their respective primary keys.
Then I have another two tables 1. Case and 2 CaseDetail. Table Case would simply hold three columns: 1. CaseId 2. CaseNo and 3. Year. Table CaseDetail would have CaseDetailId as a primary key the CaseId as a Foreign Key. Now what I need is that a particular
case could have multiple advocates and multiple petitioners. So the table CaseDetail would have two columns to hold advocateId and PartyId as a Foreign Keys.
If you look at the sample referred above you would not find how to deal with such a case. When I follow the pattern of the sample I get host of design time and runtime errors.
Therefore, please suggest what strategy should be adopted in a scenario described above while developing WPF application using Entity Framework and MVVM. -
How to create a primary key or foreign key
in the table student, sid should be the primary key
in the table prerequisite cnum should be the foreign key and prereq the primary key
please help me with the syntax thanks.As I said in your other post, it's all in the docs, go first to http://tahiti.oracle.com and try to find the answer yourself
http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/clauses3a.htm#1002630 -
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. -
Legacy Mapping Problem: Compound PK is Foreign Key
My job is to map beans using JPA onto a legacy database schema that must not get modified. I am stuck with doing the relation between two tables.
The schema is:
CREATE TABLE A (
a1 INTEGER NOT NULL,
a2 INTEGER NOT NULL,
PRIMARY KEY (a1, a2)
CREATE TABLE B (
b1 INTEGER NOT NULL,
b2 INTEGER NOT NULL,
b3 INTEGER NOT NULL,
FOREIGN KEY f (b1, b2) REFERENCES A (a1, b2) ON UPDATE CASCADE ON DELETE CASCADE,
PRIMARY KEY (b1, b2, b3)
)As you can see, both tables have compound primary keys, and the primary key of table B contains a foreign key to table A. This is typical in our DB because B in fact acts like a "inner table" (in the sense of "inner class") to A.
So far I defined both classes and provided a primary key, but the question now is, how to provide the relation between both? The relation shall be unidirectional, so that I can query all Bs belonging to one A by "myA.getBs(): Collection".
The code I have written so far is:
@Entity
public class A {
@EmbeddedId
private APK primaryKey;
@OneToMany
private Collection<B> characteristics;
@Embeddable
public class APK {
private String a1;
private String a2;
@Entity
public class B {
@EmbeddedId
private BPK primaryKey;
@Embeddable
public class BPK {
private String b1;
private String b2;
private String b3;
}Unfortunately that is not working, because the JPA Provider (here: TopLink Essentials) tries to map the relationship on a third table named "A_B" that actually is not there.
So how to tell TopLink to find the mapping information in table B (just like using the foreign key f)?
Please help, I am driving nuts!OK
So i found out the real problem
And the problem is that my CustomerHistory has a Text Field, as in a MS SQL Server TEXT Field
When i changed it to a VARCHAR, it started working
The strangest thing is that Customer also has a TEXT Field (mapped to a String) and i can do Finds without any problems
So my question now is how can i work with TEXT in CMPs ?
Thanks -
Ora-2270 Error while adding foreign key constraint on top a view
While adding a constraint, referencing a foreign key column from a view raises error. However, it works fine over a table.
Here's the sample script:
create table t_temp (
sample_id number,
text varchar2(40))
alter table t_temp add constraint temp_pk
primary key (sample_id);
create view tempvw as select sample_id,text from t_temp;
create table t_sample (
uniq_id number,
sample_id number,
sample_text varchar(40));
=========
ALTER TABLE t_sample ADD CONSTRAINT FK_sample_temp
FOREIGN KEY (sample_id) REFERENCES t_temp (sample_id);
This works fine.
=========
==============
The following raises ERROR....
ALTER TABLE t_sample ADD CONSTRAINT FK_sample_temp1
FOREIGN KEY (sample_id) REFERENCES tempvw (sample_id);
Error starting at line 1 in command:
ALTER TABLE t_sample ADD CONSTRAINT FK_sample_temp1
FOREIGN KEY (sample_id) REFERENCES tempvw (sample_id)
Error report:
SQL Error: ORA-02270: no matching unique or primary key for this column-list
02270. 00000 - "no matching unique or primary key for this column-list"
*Cause: A REFERENCES clause in a CREATE/ALTER TABLE statement
gives a column-list for which there is no matching unique or primary
key constraint in the referenced table.
*Action: Find the correct column names using the ALL_CONS_COLUMNS
catalog viewWhat exactly are you trying to accomplish by having a
referential integrity constraint on a view (which is
not allowed). PKs and FKs are allowed on views. DISABLE NOVALIDATE is the only allowed state for them. View constraints are used for query rewriting: http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/qradv.htm#sthref1457
Regards,
Dima
Maybe you are looking for
-
App-v 5.0 Sequence package that requires reboot?
Hi, I'm sequecing a package that requires a reboot. When I do the reboot, I cannot continue packaging (it does not give me the option to continue). Please advise. J. Jan Hoedt
-
Illustrator CS6 (Mac) crashes when opening large documents with drop shadows
I have a Macbook Pro ver. 10.6.8 i7 Core, 8 Gb Ram, and I am running Adobe Illustrator CS6. I have a document that is 18" x 42" and contains drop shadows. It was created using CS6. When I apply a graphic style (gradient and drop shadow) It has a prog
-
I have a very strange problem that I cannot explain or find any answers for. I upgraded to Crystal V2008 last week, and I've been running through all the reports in an application to make sure everything is working properly. Here's an example: 1)
-
How to recreate the control files
Can someone tell me how to recreate the control file? Thanks in advance Himanshu
-
We're moving towards developing J2EE applications. However, since not every single release of Oracle Application Server contains the Oracle Forms and Reports services, I'm concern about report generation of complex reports. I know Oracle has somethin