Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() {
        ...
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...