[英]An entity that associated to multiple entities
I have multiple entities like so: 我有多个这样的实体:
Public class User{
int age;
.
.
.
@OneToMany
private Set<Comment> comments = new HashSet<>();
}
and 和
Public class Product{
String name;
.
.
.
@OneToMany
private Set<Comment> comments = new HashSet<>();
}
and many more. 还有很多。 As you can see a comment could be associated with a User, Product, ...etc. 如您所见,评论可能与用户,产品等相关联。 How can I have a Comment class that do such thing? 我该如何进行这样的Comment类?
Solutions: 解决方案:
I could create a Commentable class which would look like this: 我可以创建一个Commentable类,如下所示:
Public class Commentable{ private Set<Comment> comments = new HashSet<>(); }
Then make User, Product, ..etc extends it, but this would be a problem because I have more than one class which is similar to Comment, for example Rating, then I would have a class Rateable, ...etc. 然后让User,Product,.. etc对其进行扩展,但这将是一个问题,因为我有多个与Comment类似的类,例如Rating,那么我将拥有Rateable等类。
I am sure that there is a design pattern or an object-oriented programming concept that I am missing. 我确定我缺少一个设计模式或一个面向对象的编程概念。
Many thanks 非常感谢
You can have one Comment
class as long as it is unidirectional and the owning side (who is responsible for the relation) is User
, Product
etc. That requires you to have mapping tables like UserComment
and ProductComment
and some additions to your comments
sets. 您可以拥有一个Comment
类,只要它是单向的,并且拥有方(负责关系的)是User
, Product
等。这需要您具有映射表(如UserComment
和ProductComment
以及对comments
集的一些补充。
If comments are simple they could also be embeddables instead and directly be stored in the mapping tables. 如果注释很简单,它们也可以是可嵌入的,而直接存储在映射表中。
If you don't want to use any mapping tables and want to do it the JPA way then you could use your solution option 1 with Comment
being the base class for UserComment
etc. You could then use a single table inheritance strategy and add/reuse columns for the "container" (user, product etc.) ids. 如果您不想使用任何映射表并希望以JPA方式进行操作,则可以使用解决方案选项1,其中Comment
是UserComment
等的基类。然后,您可以使用单个表继承策略并添加/重用“容器”(用户,产品等)ID的列。
A drawback with this would be that you'd then either have one additional column per container or if you reuse columns (ie the meaning of that value depends on the discriminator) your container entities need to have type compatible ids (eg all integers or strings) and you'd probably not be able to use foreign key constraints (except your database supports "partial" foreign key constraints which no db I know does). 这样做的一个缺点是您可能会在每个容器中再增加一列,或者如果您重复使用列(即,该值的含义取决于区分符),则您的容器实体需要具有类型兼容的ID(例如,所有整数或字符串) ),则您可能无法使用外键约束(除非您的数据库支持“部分”外键约束,而我所知没有db)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.