Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-To-Many Relationship with Join Table

I have a one-to-many relationship modeled using join table:

create table t1 (id int primary key, name varchar(10) /*...*/); create table t2 (id int primary key, name varchar(10) /*...*/); create table t1_t2 (t1_id int, t2_id int, primary key (t1, t2)); 

The tables are supposed to model the relationship of one t1 to many t2. What is the right way to model these tables using JPA?

like image 694
Hosam Aly Avatar asked Sep 04 '09 09:09

Hosam Aly


People also ask

How do you join a table with one-to-many relationships?

The table on the "one" side of the "one-to-many" relationship should have a primary key column. The other table should have a foreign-key defined pointing to the primary key on the first table. To return results from both tables you'd add an INNER JOIN clause to join both tables.

Which join is used in many-to-many relationship?

To get all of the records, we would use an outer join - more on that later. And there you have it - a many-to-many relationship join across three tables. Now you have this result, you can start adding whatever "where" clauses you need to get exactly the information you're after.

Is Left join one-to-many?

SQL LEFT JOIN examples Each location belongs to one and only one country while each country can have zero or more locations. The relationship between the countries and locations tables is one-to-many.

What is a one-to-many relationship?

In a relational database, a one-to-many relationship exists when one row in table A may be linked with many rows in table B, but one row in table B is linked to only one row in table A. It is important to note that a one-to-many relationship is not a property of the data, but rather of the relationship itself.


1 Answers

The typical table for one T1 to many T2 is to have a foreign key on T2 pointing toward T1. The T1_T2 table is usually not needed.

The JPA structure would then be a One-To-Many, possibly two-way.


There could be some arrangements, to make the structure you describe work. You could change T1_T2:

  • add a unique constraint on T2 (so that only one T2 is allowed)

Is that really what you want?

Edited: yes, it is what you want ;-)

I doubt you may find many examples on the net. I have no proved solution, but I would try something along these lines:

In Hibernate annotation reference documentation, see "2.2.5.3.2.3. Unidirectional with join table" to get the idea. It looks like:

    @Entity     public class Trainer {         @OneToMany         @JoinTable(             name="TrainedMonkeys",             joinColumns = @JoinColumn( name="trainer_id"),             inverseJoinColumns = @JoinColumn( name="monkey_id")         )         public Set<Monkey> getTrainedMonkeys() {         ...     } 
like image 61
KLE Avatar answered Oct 03 '22 18:10

KLE