我有Book实体和Book仓库。书有字符串数组与流派。我需要实现findAllByGenre方法来搜索所有的书籍,这些书籍将包括在数组中传递的“流派”。如何更好地实施?Book EntityBook Repository
我试图创建一个方法,它将返回图书列表,但不能理解我应该如何传递参数并使用字符串进行选择
更新:我已经尝试实现这样的仓库方法
@Repository
public interface BookRepository extends CrudRepository<BookEntity, Long> {
BookEntity findOneBySlug(String slug);
@Query("SELECT b FROM book_entity WHERE :genre in b.genre")
List<BookEntity> findAllByGenre(@Param("genre") String genre);
}
我也分享BookEntity代码
package com.uabookserver.uabookserver.entity;
import jakarta.persistence.*;
import org.springframework.lang.NonNull;
@Entity
public class BookEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NonNull
private String slug;
private String title;
private String author;
private String country;
private int year;
private String[] genre;
private int likes = 0;
private int bookmarks = 0;
private int downloads = 0;
@Lob
private String image;
@Lob
private String[] file;
public BookEntity() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String[] getGenre() {
return genre;
}
public void setGenre(String[] genre) {
this.genre = genre;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public int getBookmarks() {
return bookmarks;
}
public void setBookmarks(int bookmarks) {
this.bookmarks = bookmarks;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getDownloads() {
return downloads;
}
public void setDownloads(int downloads) {
this.downloads = downloads;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String[] getFile() {
return file;
}
public void setFile(String[] file) {
this.file = file;
}
}
和BokkService方法,用于按流派获取所有书籍
public List<Book> getAllByGenre(String genre) {
List<BookEntity> books = bookRepository.findAllByGenre(genre);
List<Book> models = this.convertToModelsList(books);
return models;
}
3条答案
按热度按时间kd3sttzy1#
JPA的美妙之处在于它在内部自动生成查询。在你的例子中,你已经传递了必要的参数作为流派数组。理想情况下,这将起作用,JPA将为您完成繁重的工作。
如果你想自己定义一个自定义的SQL查询,请参考以下内容:
Is it possible to use an Array object as a parameter in Spring Repository @Query annotation?
希望这能帮上忙。
hxzsmxv22#
谢谢你的建议,我已经找到了解决方案与原生查询这是为我工作这是代码的BookRepository方法获得所有书籍的流派
42fyovps3#
最好是这样,首先,创建一个Genre类:
图书类:
现在您可以使用查询获取Book实体;请阅读以下内容以创建查询:SQL query one to many relationship