1

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.

Ludal
  • 110
  • 1
  • 7
  • You can use a native query as well. See accepted answer [here](https://stackoverflow.com/questions/36328063/how-to-return-a-custom-object-from-a-spring-data-jpa-group-by-query) – aksappy Aug 30 '21 at 13:34
  • Your book and author class are not even defined as entities, so it is hard to answer. In general you should have a look at OneToOne-Relationships and can then either work with eager-loading or entity-graphs. – Seb Aug 30 '21 at 13:34
  • @Seb You're right, I just forgot to add these annotations, thanks! – Ludal Aug 30 '21 at 13:35
  • In your entity classes there is no relationship between two entities. – ray Aug 30 '21 at 13:37
  • @ray You're right, I've manually defined the relations in the DBMS to keep the entities simple. Should I use a `@OneToMany` relationship in all cases? – Ludal Aug 30 '21 at 13:40
  • 3
    Yes without relationship no data – Simon Martinelli Aug 30 '21 at 13:42
  • @SimonMartinelli Okay, I'm gonna use relations then. I'll post the resulting code as the answer to this question. Thanks :) – Ludal Aug 30 '21 at 14:00

0 Answers0