简体   繁体   中英

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?

Solutions:

  1. I could have multiple Comment classes for each entity, for example UserComment, ProductComment, ...etc but I believe that there is a better way to do this.
  2. I could create a Commentable class which would look like this:

     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.

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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