Java 与连接表的一对多关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1378248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:21:30  来源:igfitidea点击:

One-To-Many Relationship with Join Table

javajpapersistence

提问by Hosam Aly

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?

这些表应该模拟一个 t1 到多个 t2 的关系。使用 JPA 对这些表进行建模的正确方法是什么?

采纳答案by KLE

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.

一个 T1 到多个 T2 的典型表是在 T2 上有一个指向 T1 的外键。通常不需要 T1_T2 表。

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

JPA 结构将是一对多的,可能是双向的。



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

可能会有一些安排,以使您描述的结构起作用。您可以更改 T1_T2:

  • add a unique constraint on T2 (so that only one T2 is allowed)
  • 在 T2 上添加唯一约束(以便只允许一个 T2)

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:

Hibernate annotation 参考文档中,请参阅“2.2.5.3.2.3. Unidirectional with join table”以获取想法。看起来像:

    @Entity
    public class Trainer {
        @OneToMany
        @JoinTable(
            name="TrainedMonkeys",
            joinColumns = @JoinColumn( name="trainer_id"),
            inverseJoinColumns = @JoinColumn( name="monkey_id")
        )
        public Set<Monkey> getTrainedMonkeys() {
        ...
    }