Skip to content
Advertisement

How to search string LIKE ‘something%’ with Java Spring Framework?

I’ve got a MySQL table with Foos. Each Foo has a numeric non-unique code and a name. Now I need to find if any Foo with one of certain codes happens to have a name that starts with a given string. In normal SQL this would be trivial:

JavaScript

But how would I properly do this in Spring now? Without the need for the ‘like’ operator I’d do it like this:

JavaScript

However, with ‘like’ nothing seems to work: NAME like :name%, NAME like ':name%', or NAME like ?% when using the placeholders instead of named parameters.

I could be brutal and enter it as

JavaScript

but obviously it would be more than nice if Spring would sanitize the input parameters properly etc, you know…

You’d think Spring would support this somehow but I cannot figure it out.

Advertisement

Answer

Wait, of course I had to “try one more final thing” before calling it a day, and lo and behold, all my unit tests suddenly pass:

JavaScript

I didn’t think of entering the “%” in the parameter, I was certain Spring would automatically escape it. I wonder if I’m doing it right?

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement