[英]I want to use LIKE operator with OR operator in Jpa Spring Boot
我正在使用三個查詢參數(名稱、作者和描述)從數據庫中檢索書籍。 所以,我在 BookRepository 中使用了以下方法。
public List<BookRepoRto> findByNameOrAuthorOrDescription(String name, String author, String description);
這工作正常。 但是假設有一本書的作者是“聖雄甘地”。 但是在調用該方法時,用戶將作者的名字傳遞為“gandhi”
localhost:8070/api/bookstoreapp/books/nameorauthorordesc?name=gandhi
所以,問題在於方法
public List<BookRepoRto> findByNameOrAuthorOrDescription(String name, String author, String description);
在這種情況下不起作用。 您可以考慮描述相同的事情,因為很明顯,用戶不會在查詢參數中寫下整本書的描述來獲取他正在考慮的書籍,因為他可能不知道數據庫中的確切描述。
因此,我嘗試編寫以下方法而不是上面的方法。 在這種方法中,我嘗試將 Like 運算符與 Or 運算符一起使用,但我沒有得到所需的輸出。 請幫忙!
public List<BookRepoRto> findByNameLikeOrAuthorLikeOrDescriptionLike(String name, String author, String description);
我知道這個問題可以使用 @Query 注釋來解決,但我仍然想知道我是否可以創建可以滿足條件的所需 jpa 方法:)
當您使用Like
運算符時,您需要在參數中提供通配符。 為了獲得與您在評論中提供的等效查詢
SELECT * FROM books b
WHERE b.name LIKE :name%
or b.author LIKE %:author%
or b.description LIKE %:description%
你應該使用
findByNameStartsWithOrAuthorContainsOrDescriptionContains(
String name,
String author,
String description
)
請參閱https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords
您可以為此使用規范功能。 它使您能夠使用類似 FP 的樣式組合不同的謂詞: https ://www.baeldung.com/spring-data-criteria-queries
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.