1 year ago

#361505

test-img

user99536

Spring Data Rest search sub-resources

I'm writing a Spring Data Rest application and trying to find a way to search for a resource not only on the main collection resource, but also within the association resource on its parent.

For example, if I have a Library entity and a Book entity with a one-to-many relationship:

@Entity
public class Library {
  @Id
  private Long id;

  private String libraryName;

  @OneToMany(mappedBy = "library")
  private List<Book> books;
}
@Entity
public class Book {
  @Id
  private Long id;

  private String title;

  @ManyToOne
  @JoinColumn(name="library_id")
  private Library library;
}

And I have a findByTitle method on BookRepository:

public interface BookRepository extends CrudRepository<Book, Long> {
  List<Book> findByTitle(String title);
}

I can search all books by title with /books/search/findByTitle?title=title

But what if I want to search for books by title within a particular library, like /libraries/1/books/search/findByTitle?title=title? Is there a way to do this in Spring Data Rest?

I know I can add a search method with multiple parameters like

List<Book> findByTitleAndLibraryId(String title, Long libraryId);

But it seems like it would be useful to scope this search to the URL of the parent resource if, for example, a user was only authorized to search for books within certain libraries.

java

spring

spring-data-rest

0 Answers

Your Answer

Accepted video resources