简体   繁体   中英

JPA @Query to handle null parameter value and like %?1%

@Query("select t from Menu t where (?1 is null or t.name like %?1%)")

in my case , this can handle null values, but when i have no null value like %?1% no effect , there is no way to do a fuzzy search .

I would like to have code=4 and find

4
546
345

but only find

4

Any help?

The feature you are trying to use got introduced with ticket DATAJPA-292 and in the comments you'll find the limitation that is causing problems to you:

One thing to note is that references to the same parameter can only be equipped with the very same LIKE expression. The following query snippet is invalid:

 … firstname like %?1 and lastname like ?1% 

As we can only bind a single parameter once.

To get around that limitation you should be able to use SpEL expressions. Try the following:

@Query("select t from Menu t where (?1 is null or t.name like ?#{'%'+[0]+'%'})")

Not 100% sure, but I think this should work as well because it basically considers the to bind instances as separate parameters:

@Query("select t from Menu t where (?1 is null or t.name like %?#{[0]}%)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM