0

I am working on my school project and kind of replicating Stack Exchange site (project purpose only)

There is a table called Posts which might be a Question same as an Answer, based on PostTypeId. When it is a Question, it's column called AcceptedAnswerId is populated. However, there is no column listing all Answers for that Question.

The only relation between the Question and it's Answers is a column ParentId in the Answers. Meaning @ManyToOne

Now I need to get all Answers per that Question.

Any idea whether such thing is even possible?

So far, I've got something like this:

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "ParentId", referencedColumnName = "Id")
public Post getParentPost(){
    return parentPost;
}

public void setParentPost(Post parentPost) {
    this.parentPost = parentPost;
}
asgs
  • 3,718
  • 6
  • 36
  • 49
Ondrej Tokar
  • 4,298
  • 7
  • 42
  • 98

1 Answers1

0

Simplest way is to also map the other end like this :

@OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY, mappedBy = "ParentPost")
public List<Post> getChildPosts();

see also JPA JoinColumn vs mappedBy

Community
  • 1
  • 1
Mikey
  • 589
  • 1
  • 11
  • 18
  • Thank you, but I am having an error on the FetchType.Lazy... when I change it to Eager it makes some kind of infinite loop result. Like a recursive retrieval... – Ondrej Tokar Nov 23 '15 at 11:26
  • try @OneToMany( mappedBy = "parentPost") - i have here no java ee environment to test :( – Mikey Nov 23 '15 at 11:55
  • I just had to add @JsonIgnore, into one of the fields which was causing the infinite circulation-like effect. But basically your answer is correct :) – Ondrej Tokar Nov 23 '15 at 15:08