简体   繁体   English

具有2个外键选项的休眠实体

[英]Hibernate Entity with 2 foreign key options

I have that use case: 我有那个用例:

I have table A and table B (none of them is extending the other, they are logically different). 我有表A表B (它们都没有扩展另一个,它们在逻辑上是不同的)。 Both tables should have a link with one or more 'documents' . 两个表都应具有一个或多个“文档”的链接。 So I can design table A and table B, but how to design the table for the 'documents'? 因此,我可以设计表A和表B,但是如何为“文档”设计表呢? Should it have 2 foreign key constraints (there is a possibilite one record from documents to have only 1 foreign key to Table A or B and the other foreign key will be null)? 它应该有2个外键约束吗(文档中有一个记录可能只对表A或B有1个外键,而另一个外键将为空)? How I will declare that in SQL and in Hibernate/JPA. 我将如何在SQL和Hibernate / JPA中声明这一点。 Thanks in advance. 提前致谢。

You can have one-to-many unidirectional relationship from Table A/B to documents. 从表A / B到文档,您可以具有一对多的单向关系。 By doing so, you will require link tables between Table A/B and document (in other words, document will be a master table). 这样,您将需要在表A / B和文档之间建立链接表(换句话说,文档将是主表)。 Also you will require to store document separately first and then can assign the documents to the Table A/B entities. 另外,您将需要先单独存储文档,然后才能将文档分配给Table A / B实体。

Alternatively, if want to save the documents along with Table A/B entity, then you need to maintain both foreign keys which will be nullable ie either A or B. 或者,如果要将文档与表A / B实体一起保存,则需要维护两个可以为空的外键,即A或B。

Both approaches are fine hence depending on your business requirement you should pick one. 两种方法都很好,因此应根据您的业务需求选择一种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM