我正在使用三個查詢引數(名稱、作者和描述)從資料庫中檢索書籍。所以,我在 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 方法:)
uj5u.com熱心網友回復:
使用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
uj5u.com熱心網友回復:
您可以為此使用規范功能。它使您能夠使用類似 FP 的樣式組合不同的謂詞:https ://www.baeldung.com/spring-data-criteria-queries
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/498178.html
上一篇:引數值[2019-05-15,23:00]與預期型別不匹配[java.time.LocalDateTime(n/a)]
