简体   繁体   中英

Get All Foreign Keys to Unique indexes from Oracle using JDBC

I have a table with foreign key to a Unique column in another table. I can see that the foreign key is correctly defined but when I try to get it using below mentioned code using JDBC I dont see it. I have verified that this works when foreign key references a primary key of another table.

So my question is "How do I get foreign keys to Unique indexed columns in Oracle using JDBC?" .

ResultSet rset = databaseMetaData.getImportedKeys(null, dbName, tableName);

while(rset.next()){
  String column_name = rset.getString("FKCOLUMN_NAME");
  String pk_table = rset.getString("PKTABLE_NAME");
  String pk_column = rset.getString("PKCOLUMN_NAME");
  String constraint_name = rset.getString("FK_NAME");

  System.out.println(column_name + " ==> " + pk_column + "(TBL:" + pk_table + ")(CN:" + constraint_name + ")");
}
rset.close();

Additional Info : Someone had suggested using getCrossReference but the problem with that is that I need to know both the source and target tables for the referential constraint beforehand which I don't. Also I am looking for a pure jdbc api solution that does not employ any special Oracle schema or queries. My application deals with multiple databases but I try to hide it behind a layer of generic jdbc api.

I would suggest in your case that you use the catalog views. In Oracle catalog views you will find all the metadata that describe an Oracle database:

http://www.oracle.com/pls/db92/db92.catalog_views

For example, to get all the foreign keys from a certain table:

select * from all_constraints constraints where constraints.table_name = 'MY_TABLE' and constraints.constraint_type = 'R'

There is a deeper and better answer here:

Oracle get foreign keys

Using getCrossReference from the JDBC DatabaseMetaData would be the preferred solution. Using null or "%" as the parentTable argument will list all of the foreign keys of the specified foreignTable .

However, after taking a look at the Oracle JDBC driver API of the getCrossReference it would seem that Oracle driver does not specify that foreign keys referencing unique keys will be listed. I tried it out and sadly it seems there is no way of getting the list of all foreign keys using only pure JDBC API. You can only get a list of foreign keys referencing primary keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM