jan
jan

Reputation: 4103

JPA - Mapping entity to more than one other entity

I have two Entities that can be commented by user (lets say for example: news and articles). Is it possible to use one Comment Entity and attach them to the both entities?

I tried it by creating an abstract super class (AbstractCommentableEntity), that handles the relationship to the comments (would be CommentabeEntity1 and CommentabeEntity2). The news and article entities then would extend this class and it would be possible to attach comments to them. See my image as well as my code.

But if I implement it like that, I get an Mapping exception. I think thats because I try to map a @MappedSuperclass annotated class. Is there any way how I can get this running?

enter image description here

My comment entiy would look like this:

@Entity
public class Comment {

    private AbstractCommentableEntity commentableEntity;

    @ManyToOne
    @JoinColumn
    public AbstractCommentableEntity getCommentableEntity() {
        return commentableEntity;
    }

    public void setCommentableEntity(AbstractCommentableEntity commentableEntity) {
        this.commentableEntity = commentableEntity;
    }
}

The abstract superclass for the commentable entities would look like:

@MappedSuperclass 
public abstract class AbstractCommentableEntity {

    Set<Comment> comments = new HashSet<Comment>();

    @OneToMany(mappedBy = "commentableEntity")
    public Set<Comment> getComments() {
        return comments;
    }

    public void setComments(Set<Comment> comments) {
        this.comments = comments;
    }
}

And a specific entity would just extend it like that:

public class CommentabeEntity2 extends AbstractCommentableEntity{

}

Upvotes: 1

Views: 109

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

You shouldn't make the association bidirectional: a comment would thus be a general-purpose entity, that can be attached to any kind of entity. The News and Article entities would both have a collection of comments.

By default, this would be mapped using two join tables: one linking Comment and News, and another one linking Comment and Article.

If you really want the association to be bidirectional, then you could use an AbstractComment entity, with two sub-entities: NewsComment and ArticleComment. NewsComment would have a bidirectional ManyToOne association with News, and ArticleComment would have a bidirectional ManyToOne association with Article.

Upvotes: 0

Related Questions