Spring Data Rest 搜索子资源

发布于 2025-01-18 03:45:44 字数 1239 浏览 1 评论 0原文

我正在编写一个 Spring Data Rest 应用程序,并试图找到一种不仅在主集合资源上搜索资源,而且还在其父级的关联资源中搜索资源的方法。

例如,如果我有一个 Library 实体和一个具有一对多关系的 Book 实体:

@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;
}

并且我有一个 findByTitle 方法BookRepository

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

我可以使用 /books/search/findByTitle?title=title 按书名搜索所有书籍,

但是如果我想在特定图书馆内按书名搜索书籍怎么办?喜欢/libraries/1/books/search/findByTitle?title=title?有没有办法在 Spring Data Rest 中做到这一点?

我知道我可以添加具有多个参数的搜索方法,例如,

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

但如果例如用户仅被授权在某些图书馆中搜索书籍,则将此搜索范围限制为父资源的 URL 似乎会很有用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文