How to find relationship between two tables?
In the SQL, we need to write a lot, multi-level join. but the problem is, we don't now how to connect those tables?
For example, Table_A
reference Table_B
, Table_B
reference Table_C
using foreign key. How to get all this relationship route map? Do we have a free open souce to开发者_如何学编程ol to get relationship between ANY two tables if applicable?
I prefer Java code.
You can use SQL Power Architect to obtain a data model by reverse engineering a database. The Community Edition is capable of doing it.
I maybe you mean how to get foreign key from metadata. Basically foreign keys defines realations.
Here is an example how to get foreign keys from jdbc metadata: http://www.java2s.com/Code/Java/Database-SQL-JDBC/GetForeignKeys.htm
Also you can use hibernate tools to reverse engineer database to domain entities. Where you can clearly see relations.
java.sql.DatabaseMetaData interface exposes meta information about the database. Specifically this method exposes foreign key relationships:
public ResultSet getCrossReference(String primaryCatalog,
String primarySchema,
String primaryTable,
String foreignCatalog,
String foreignSchema,
String foreignTable)
throws SQLException
Java doc:
Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key columns of the given primary key table (describe how one table imports another's key). This should normally return a single foreign key/primary key pair because most tables import a foreign key from a table only once.
精彩评论