2

I'm currently building a REST API in spring, and would like to add a search method which takes in a list of letters and search for sequences based on those letters. The code I have below is an example of what i've achieved so far. It does the job, and searches based on the letter parameters. But it's limited to have to use exactly the number of params specified in the method.

@Query("SELECT f FROM Item f " +
        "WHERE LOWER(f.title) LIKE CONCAT(" +
        "  '%',LOWER(:letter1)," +
        "  '%',LOWER(:letter2)," +
        "  '%',LOWER(:letter3)," +
        "  '%',LOWER(:letter4),'%')")
@RestResource(rel = "title-fragmented", path="findByFragments")
Page<Item> findByFragmented(@Param("letter1") String letter1,
    @Param("letter2") String letter2,
    @Param("letter3") String letter3,
    @Param("letter4") String letter4,
    Pageable page
);

I was wondering if it is possible to achieve the same result without specifying the number of letters to be concatenated. So for example when

/api/v1/search/findByfragments?letter=A&letter=B&letter=C.... 

is called, it'll work. I've tried passing string arrays as a the @Param value, but couldn't get it to work.

Thanks in advance.

1
  • Pass a single String parameter, and do the % concatenations before calling this method. Or create a custom repository method, and do whatever you want, programmatically. Commented Jan 27, 2018 at 16:01

1 Answer 1

1

Solved my issue by using SpEL expressions to split apart a single string, and replace the letters between them with wildcard(%) expression. Example below for anyone who may find themselves with the same issue:

@Query(
  "SELECT f FROM Item f WHERE LOWER(f.title) LIKE CONCAT('%',LOWER(:#{#title.replaceAll('','%')}),'%')"
)
@RestResource(rel = "item-title-by-fragments", path="fragments")
Page<Item> findUsingFragments(@Param("title") String title, Pageable page); 
Sign up to request clarification or add additional context in comments.

1 Comment

I will do when allowed, you have to wait a couple of days until after the question has been created. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.