ORM:是否可以将外键解析为两个不同的关系?

ORM: Is it possible to resolve a foreign key to two different relationships?

问题

我将提供一个简单的例子来描述我目前在一个更大的项目中面临的问题。

在数据库级别,我想创建两个 table:事件和参与者。 事件以 1-n 关系与参与者相关联。

在应用程序级别,我想根据它们的类型将这两种关系分开。 事件 class 包含访问者列表和 eventService 列表(均为参与者类型)。

问题


任何帮助深表感谢。
  1. 是的,这是可能的 :) 您可以创建将映射到数据库中的单个 table 的对象层次结构。例如在 spring jpa + lombok:
    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    public  class Person{
        @Id @GeneratedValue @Getter
        private long id;
    }

    @Entity
    @DiscriminatorValue("VST")
    public class Visitor extends Person{
    }

    @Entity
    @DiscriminatorValue("ES")
    public class EventService extends Person{
    }

    @Entity
    public class Event{
        @Id @GeneratedValue @Getter
        private long id;
        @OneToMany
        private List<Visitor> visitorList;
        @OneToMany
        private List<EventService> eventServiceList;
    }

免责声明:我没有测试过这个例子,所以可能会有一些错误:)

  1. 有很多因素需要考虑,还有很多“个人品味”。这种方法本身没有好坏之分。在评估时,值得考虑数据库性能和架构的可扩展性。