与连接表的一对多关系 [英] One-To-Many Relationship with Join Table

查看:75
本文介绍了与连接表的一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用连接表建模的一对多关系:

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));

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

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的典型表格是T2上的外键指向T1。通常不需要T1_T2表。

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.

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

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

为了使你描述的结构有效,可能会有一些安排。你可以改变T1_T2:

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


  • 在T2上添加一个唯一约束(这样只允许一个T2)

这真的是你想要的吗?

已编辑:是的,它是你想要什么; - )

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:

Hibernate注释参考文档,参见2.2.5.3.2.3。带有连接表的单向获取这个想法。它看起来像:

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

这篇关于与连接表的一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆