Let's say I have these two entities:
Book.java
@Entity
public class Book {
public Integer id;
public Integer authorId;
public String title;
}
Author.java
@Entity
public class Author {
public Integer id;
public String firstName;
public String lastName;
}
How can I query all the books, along with their author? Something like
public interface BookRepository implements JpaRepository<Book, Integer> {
@Query("FROM Book b JOIN FETCH Author a ON b.authorId = a.id")
List<BookWithAuthor> findAllWithAuthor();
}
Where BookWithAuthor
is the following:
public class BookWithAuthor {
public Integer id;
public String title;
public Author author;
}
So far, I've done some research, and came across these solutions (which do not suit me):
- Solution 1 ("ProductRepository Interface"): you need to enter the full package name and call a constructor
- Solution 2: it uses the EntityManager, which I don't want.
How can I achieve my goal?
Thanks.