Sam
Sam

Reputation: 1304

Spring REST @Query variable parameters

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.

Upvotes: 2

Views: 1196

Answers (1)

Sam
Sam

Reputation: 1304

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); 

Upvotes: 1

Related Questions