views:

20

answers:

1

I am creating a website that will have articles; each article will have comments. These comments will be stored in a "comment" table with a field called "parent_id" that is a foreign key to the field "id" in the same table.

I am hoping to use Hibernate to recursively grab all of the comments for a specific article.

Here is my Entity:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.hibernate.annotations.IndexColumn;

@Entity
public class Comment implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    @ManyToOne
    @JoinColumn(name="user_id")
    private User user;
    @OneToMany(targetEntity=Comment.class)
    @JoinColumn(name="parent_id")
    @IndexColumn(name="id", base=0)
    private List<Comment> comments = new ArrayList<Comment>();
    @Column(name="article_id", length=10)
    private int articleId;
    @Column(name="text", length=8192)
    private String text;

    public int getArticleId() {
        return articleId;
    }

    public void setArticleId(int articleId) {
        this.articleId = articleId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }



    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Comment [" + "articleId " + articleId + " " + "id " + id + " "  + "text " + text + " " + "]";
    }


}

The code is "kinda" working, however, when all of the comments are retrieved the "child" list of comments contains the same number of elements as there are total comments (if that makes sense. For instance, assume I have only three comments in the table for article with id number 1... this article with 2 comments, and one of the comments has a child comment.. the array with the child comment has 3 entries, the first 2 are null and the last is the child comment.

Is this code correct?

+1  A: 

I wonder if the problem is not coming from the fact that you are using the PK column as index column. I'd recommend to use a dedicated column for the index column. Something like this:

@OneToMany
@JoinColumn(name="parent_id")
@IndexColumn(name="comments_index", base=0)
private List<Comment> comments = new ArrayList<Comment>();

Could you give this a try?

Pascal Thivent
Thanks, this seems to have solved my issue.
El Guapo
@El You're welcome, glad it's solved.
Pascal Thivent