Home > other >  Find all data using foreign key from referenced table in spring boot jpa
Find all data using foreign key from referenced table in spring boot jpa

Time:05-04

I have done the jpa one to many mapping between Book & corresponding Pages as follows.

@Entity
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Book {
    @Id
    @EqualsAndHashCode.Include
    @Column(name = "book_id")
    private String bookId;

    private String name;

    @OneToMany(targetEntity = Page.class, cascade= CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "book_id_fk", referencedColumnName = "book_id")
    private List<Page> pages;
}

and

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Page {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer sno;

    private Integer number;
}

@Repository
public interface PageRepository extends JpaRepository<Page, Integer> {
    List<Page> findAllByBook_Id(String bookId);
}

Now I would like to get all pages using book id from Page table. For that I'm using findAllBook_id method but I'm getting the No property book found for type Page! exception. I tried XXXBook_fkId/XXXBookFkId/XXXBook_fk_id etc. method names but didn't worked out. Kindly help

CodePudding user response:

The problem that you face is that your entity Page does not have a field that relates with Book. So you have unidirectional mapping in JPA layer.

One solution would be to include the following custom query which will return you what you expect to be returned.

 @Query( "SELECT pg FROM Book bk join bk.pages pg WHERE bk.bookId = :bookId")
 List<Page> findPagesByBookId(@Param("bookId") String bookId);
  • Related