2014-07-09 33 views
15

在Spring-data JPA中,是否有創建一個方法查詢,本質上是通過類似搜索?SpringData JPA存儲庫方法查詢類似?

我有以下方法查詢

public MakeModel findByModelIgnoreCase(String model); 

我真正想要的是一個類似的表達。我是否需要創建Criteria或@Query註釋?我問得太多了嗎?

//Stupid example of what I want to be able to do 

    public MakeModel findByFuzzyModelIgnoreCase(String model); 

真的,我想在它的核心,我想做一個表搜索。我在Spring Data下使用Hibernate,所以我想我可以使用一些像Hibernate Search這樣的搜索API。我接受這裏的建議。

+0

JPQL具有類似:https://blogs.oracle.com/JPQL01/entry/how_to_use_like_expression –

+1

http://docs.spring.io/spring-data/jpa/docs/1.6.1.RELEASE/reference/ html/jpa.repositories.html#jpa.query-methods.query-creation – axtavt

+0

axtavt正是我所需要的... – chrislhardin

回答

20

喜歡的是支持太:

MakeModel findByModelLikeIgnoreCase(String model); 

當你調用該方法使用follwing: 在開始添加"%"地說,沒關係是一個嚴格的開始匹配, 同在最後,或者你可以使用其中之一,這取決於你想要的。

MakeModel makeModel = findByModelLikeIgnoreCase("%"+model+"%"); 

如果你的品牌型號是test和比較字符串是"%"+model+"%"則:

es is a match , T is a match , test is a match 

字符串來比較是model+"%"

te is a match , es is not . 
+4

很好的回答!您可能想提一下「Containing」/「Contains」關鍵字,但這些關鍵字不需要客戶端知道特定商店的相似語法。 –

23

如果你不這樣做想要手動添加「%」,可以使用以下查詢方法:

MakeModel findByModelStartingWithIgnoreCase(String model); //SQL => LIKE 'model%' 
MakeModel findByModelEndingWithIgnoreCase(String model); //SQL => LIKE '%model' 
MakeModel findByModelContainingIgnoreCase(String model); //SQL => LIKE '%model%' 
+0

1個小細節,IgnoreCase => ILIKE – dwana