mrks_
mrks_

Reputation: 369

Storing structured comments in MYSQL database using Java JPA and Spring Data

Using Spring Data and Java JPA, I would like to store comment threads in a MYSQL table. The comments are on some chunk of data, and every comment can have any number of child comments (think Reddit). I was wondering if this Java class makes sense to fulfill my needs.

@Entity
public class Comment extends Identified {

    // Comment data
    @Column(nullable=false)
    private String data;

    // Parent comment
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(nullable=true)
    private Comment parent;

    // Sub comments
    @OneToMany(fetch=FetchType.EAGER)
    @JoinColumn(nullable=true, mappedBy="parent")
    private Set<Comment> children;

    public Comment() { }
    ....

To clarify, my main concern regards having both a ManyToOne and OneToMany relationship to the same class. It seems ugly, but also like the only way to express this relationship.

Upvotes: 2

Views: 557

Answers (1)

Ondro Mih&#225;lyi
Ondro Mih&#225;lyi

Reputation: 7710

I assure you that your mapping is completely normal, I would even say usual. The two relationships (many-to-one and one-to-many) are realized in DB using different concepts and do not collide. As the relationship is bidirectional, both mappings represent different ends of two different links (one is relation to parent, another is relation to child).

Upvotes: 2

Related Questions