Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringData JPA Repository Method Query with a like?

In Spring-data JPA, is there anyway to create a method query that is essentially searches by like??

I have the following method query

public MakeModel findByModelIgnoreCase(String model);

What I really want is a like expression. Do I need to just create a Criteria or a @Query annotation? Am I asking too much?

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

    public MakeModel findByFuzzyModelIgnoreCase(String model);

Really I guess at the heart of it, I want to do a table search. I'm using Hibernate underneath Spring Data so I guess I could use some search api like Hibernate Search. I'm open to recommendations here.

like image 763
chrislhardin Avatar asked Jul 09 '14 20:07

chrislhardin


2 Answers

If you don't want add "%" manually, you can use the following query methods:

MakeModel findByModelStartingWithIgnoreCase(String model); //SQL => LIKE 'model%'
MakeModel findByModelEndingWithIgnoreCase(String model); //SQL => LIKE '%model'
MakeModel findByModelContainingIgnoreCase(String model); //SQL => LIKE '%model%'
like image 107
UUHHIVS Avatar answered Nov 18 '22 05:11

UUHHIVS


Like is supported too:

MakeModel findByModelLikeIgnoreCase(String model);

When you call the method use the follwing: Add "%" at the start to say that it doesn't matter to be a strict start match , the same at the end, or you can use one of them it depends on the like you want.

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

if your make model Is test and the string to compare to is "%"+model+"%" then :

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

the string to compare to is model+"%":

te is a match , es is not .
like image 23
Rafik BELDI Avatar answered Nov 18 '22 05:11

Rafik BELDI