【问题标题】:How do I repsent OneToMany relationship in JPA with multiple tables inbetween?如何在 JPA 中用多个表表示一对多关系?
【发布时间】:2014-02-05 18:34:15
【问题描述】:

在高层次上,我有一个“MainClass”类,它有一个“OtherEntity”列表。基本上有两个连接表。这两个连接表中有其他组件使用的元数据,但我没有定义实体,因为我们在连接操作之外不需要它们。但基本上 MainClass => TableOne => TableTwo => OtherEntity

我的实体定义

@Entity
public class MainClass {

    // other stuff ...

    // how to?
    @OneToMany
    private List<OtherEntity> otherEntities;
}


@Entity
public class OtherClass { // other stuff ... }

我的架构(旧版,无法修改)

table MainClass
    PK id
    ...

table TableOne
    PK id
    FK main_class_id
    FK table_two_id

table TableTwo
    PK id
    FK table_one_id
    FK other_entity_id

table OtherEntity
     PK id
     ...

如果可以的话,我想避免为 TableOne 和 TableTwo 创建实体。

【问题讨论】:

    标签: java jpa eclipselink spring-data-jpa


    【解决方案1】:

    考虑使用 @SecondaryTable 它应该适用于遗留模式,使用此注释您可以在一个实体中拥有字段,并且只需定义哪些字段将构成其他表的一部分,但您只有 2 个实体。

    查看this教程

    想法是从不同表中的一个实体拆分字段,无需创建其他实体,只需定义哪些字段在哪个表中。

    @SecondaryTables{@SecondaryTable(name="XX")} 
    

    在表格之间移动字段使用

    @Column(table="XX")
    

    在您的配置中尝试这样的操作。

    @Entity
    @SecondaryTables{@SecondaryTable(name="TableOne"), @SecondaryTable(name="TableTwo")}
    table MainClass
        PK id
        @Column(table="TableOne")
        FK main_class_id
        @Column(table="TableOne")
        FK table_two_id
    
        @Column(table="TableTwo")
        PK id
        @Column(table="TableTwo")
        FK table_one_id
        @Column(table="TableTwo")
        FK other_entity_id
    

    对于中间表中的 ID,请考虑删除 @Id 并自动设置它,它应该可以工作!

    【讨论】:

    • 这是一个有趣的概念。但是,不应该在 OtherEntity 类上注释 @SecondaryTables 以便它从其他表中提取 FK 吗?
    • 嗯,需要检查设计,可能更有意义的是两个在一个实体上,其中一些在另一个实体中,其他实体在另一个实体中,考虑审查你的设计以应用 SecondaryTables 时更有意义.它可以帮助您考虑像我的答案 XD
    • 我很欣赏对辅助表的洞察力,因为它可能会为不同的问题提供用途。然而,我不知道我们有一个提供统一表格的视图。我只是将joinTable注解指向视图,问题就解决了。
    【解决方案2】:

    这个问题是最终会得到解决的设计问题。我们有一个提供统一查找表的数据库视图。在数据库层,我们可以单独分配碎片。

    @Entity
    public class MainClass {
    
        @OneToMany
        @JoinTable(name = "TheViewName", 
            joinColumns = @JoinColumn(name = "id", insertable = false, updatable= false), 
            inverseJoinColumns = @JoinColumn(name = "other_id", insertable = false, 
                updatable = false))
        private List<OtherEntity> otherEntities;
    }
    

    这意味着我不能将新的其他实体分配给 MainClass 并保持两者。我必须做两个单独的操作才能完成。但是,当我们重构模式时,这种情况就会消失。

    或者,我们可以为其他两个表创建实体以使操作更加透明。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-08
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2016-01-03
      • 2018-01-22
      • 1970-01-01
      相关资源
      最近更新 更多