How to find relationship between two tables? - java

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 tool 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.

Related

Pogrammatically get foreign keys for a table in jOOQ

Is there a way to programmatically list all the Fields which are a Foreign Key in jOOQ? It generates a lot of static constants to foreign keys, but there is no good way to programmatically access these.
Example, I have a table Orders with a foreign key field customer_id. In jOOQ, say I have a reference to said table object for Orders, there does not appear to be a way to programmatically get a reference to the customer_id jooq field object. So my only solution now is to manually make these mappings somewhere using a literal map datastructure. Seems like jooq would have been able to do this for me, am I missing something?
There are many ways to navigate the jOOQ meta model. Your description isn't complete, but I'm assuming, you would want to do something like this:
for (ForeignKey<?, ?> fk : ORDERS.getReferencesTo(CUSTOMER))
for (Field<?> fkField : fk.getFields())
System.out.println(fkField);

JPA Composite Key for one Table and a Primary Key for another Table - Possible?

Is it possible to have both a composite key and a primary key in the same Domain Model (Entity Class) so that some tables (queries) are joined using the composite key and other tables (queries) are joined using the primary key?
I'm dealing with legacy applications and I have limited access to changing the underlying database. Some of our queries are expecting a single row result but are getting many rows because of flaws in our database design. We can fix this problem by introducing a composite key to one of our Domain Models but doing so will affect many (many) other components that rely on the original primary key.
From my understand of JPA and the reading I've done so far on this matter I do not think this is possible but I thought it would be worth a shot to reach out to others who may have had a similar problem.
The table has only one primary key, so you have no options to choose which primary key to use. Also, i can't understand why you going to have differences between database original model and JPA. Actually, getting single row instead of many rows is where clause's task.
You said some of your queries fails after adding composite pk, so may be you just made your composite pk in wrong way?
Anyway, here is nice example or implementation composite pk, may be it will help you:
Mapping ManyToMany with composite Primary key and Annotation:
Maybe you should give a different look at your problem.
If your queries are returning multiple and different rows, then you should be able to resolve this using a more specific WHERE clause;
If your queries are returning multiple and equal rows, you should try the DISTINCT clause inside your query, example:
SELECT DISTINCT e FROM br.com.stackoverflow.Entity e

It is possible to maintain relation between two table in Hibernate level?

I am new to Hibernate. Can you please answer my question?
Is it acceptable to maintain the 2 table relations in ORM level? I dont want to add foreign key relation between two tables, but I would like to add many to one relation in hbm file.
Ex I have Account and Account_Type tables. Account table contain AcntType column. Its not null column. AccountType contain AcntType as PK. There is no FK relation in Account table.
Now I would like to add relation from ORM level, I don't want to alter Account table and add foreign key constraint now.
I would like to add "many-to-one" attribute in my Account hbm file. I would like to add "one-to-many" attribute in my AccountType hbm file.
Is it acceptable to maintain relation in ORM level nor from DB level. I am using Oracle DB
Hibernate doesn't care if there is a foreign key constraint or not between the tables.
But adding a foreign key constraint guaranteees that, whatever you use to update your database, and whatever bug your code could have, you'll never have an account referencing an account type that does not exist. So you should definitely have a foreign key constraint.

JPA: InvalidStateException Error + Composite Key/EmbeddableId/Sequence Generated IDs

I currently have a schema set up with my database and Java Application using OpenJPA that works most of the time, but sometimes I get the error for a few users:
org.apache.openjpa.persistence.InvalidStateException: Attempt to set column "table1.ID" to two different values
table1 actually has a composite Key (two values) and each value in that key is a foreign key to another table. I used RSA (Rational Software Architect) to set up the entities for me (generated code). It set up a PK class (using #EmbeddableId to reference the PK class) in the Entity class for table1, and then two #ManyToOne relationships in the same table1 Entity class (and also in the entity classes that those columns reference) since they are foreign keys
Now, as I mentioned above, each value in the composite key is a foreign key. Well, each of those foreign keys is actually generated using an outside Sequencer in their own entity classes. I am using DB2 and using #GeneratedValue on the columns (i.e. the IDs in table2's and table3's entity classes). I use strategy=GenerationType.SEQUENCE also for each.
Again, everything works USUALLY but not 100% of the time and I'm unsure why. I have gotten rid of this error by wiping out everything and resetting the Sequence Generators, but I know this is definitely not a solution. Could it have something to do with the fact that the two Composite Key values in the database are foreign keys to columns which were generated using a sequence, but the PK entity might not know?
I have noticed too that it only works for users who have a record in the Users table (one of the foreign keys mentioned above is to a Users table, while the other FK is to another table). What happens, if a user is not in the table, it creates one, something like:
User newUser = userManager.getNewUser();
newUser.setName(..);
newUser.setEmail(..);
...
When it's done, the PK class I mentioned above has a new instance of that created, which is then called into another table. The ID from the user above is passed into the PK. Like:
PK newPK = pkManager.getNewPK();
newPk.setAID(newUser.getID());
Has anybody run into this? Any solutions?
Sorry, fixed the problem. I went through my code and realized I had forgot to refactor one line of code (change in data model).

Relational Database (H2, Java): How do I constrain a foreign key to NOT match another foreign key in the same table?

Simple question. Just wondering if this can be done without me having to enforce this constraint manually in my Java code. These two foreign keys (together in the same table) both refer out to another table, but for each row, they must not be allowed to point to the same foreign item.
link text
You can use a check contraint to enforce that two columns have different values:
ALTER TABLE TableName
ADD CONSTRAINT ConstraintName
CHECK fk1 <> fk2

Categories

Resources