I have a similar setup as in this question, i.e., one Author can have multiple Comments. In my case, it is modeled as OneToMany in the Author class.
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userName;
@OneToMany()
@JoinTable(name = "AUTHOR_COMMENTS")
private List<Comment> comments;
}
JPA created a reference table to implement this relation, hence the @JoinTable annotation.
Now, I want to query the author with all its comments in a single query.
The answer from here suggests that this should be possible in JPQL by selecting the list of comments in the query.
@Query(value= "SELECT a.userName as userName, a.comments as comments from Author a")
List<AuthorProjection> authorsWithComments();
Note that in my case the result is projected to relevant fields.
public interface AuthorProjection {
String getUserName();
List<CommentProjection> getComments();
}
The problem is that JPA returns only a single comment in the list.
I get:
John Doe, [First comment]
John Doe, [Second comment]
But I want:
John Doe, [First comment, Second comment]
So, I want all comments returned in the list of the corresponding author, all using just one single query.
- Is this even possible?
- Do I need to configure anything (I use an H2 database)?
- Are there requirements on the domain model to make it work (e.g. backreference from Comment to Author needed)?
I found other answers mentioning JOIN FETCH and SELECT NEW. But I was not able to make it work with JOIN FETCH. And SELECT NEW does not seem applicable because I already use a projection interface.