mardi 21 août 2018

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

Aucun commentaire:

Enregistrer un commentaire