ORM:是否可以将外键解析为两个不同的关系? [英] ORM: Is it possible to resolve a foreign key to two different relationships?
本文介绍了ORM:是否可以将外键解析为两个不同的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将提供一个简单的例子来描述我目前在一个更大的项目中面临的问题.
I am going to provide a simple example which will describe the problem I am currently facing in a larger project.
- 一个活动有 n 个参与者
- 这些参与者可以有不同的角色(例如访问者、事件服务)
- 一个参与者不能以两个不同的角色参加同一个活动
在数据库级别我想创建两个表:Event 和 Participant.事件与参与者以 1-n 关系连接.
On the database level I want to create two tables: Event and Participant. Event is connected with Participant in a 1-n relation.
在应用程序级别,我想根据它们的类型将这两种关系分开.事件类包含一个访问者列表和一个 eventService 列表(均为 Participant 类型).
On the application level I want to separate these two relationships depending on their type. The event class holds a list of visitors and a list of eventService (both of type Participant).
- 是否可以使用 ORM 抽象(例如 Spring-Hibernate 或 TypeORM)来实现这一点?
- 一般来说,这是否是一种好方法(如果不是,是否有更好的选择而不复制表格)?
推荐答案
- 是的,这是可能的 :) 您可以创建将映射到数据库中单个表的对象层次结构.例如在 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;
}
免责声明:我没有测试过这个例子,所以可能会有一些错误:)
- 需要考虑很多因素以及很多个人品味".这种方法本质上没有好坏之分.在评估时,值得考虑数据库性能和架构的可扩展性.
这篇关于ORM:是否可以将外键解析为两个不同的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文