Search code examples
sqlspringjpaspring-data-jpasql-like

Spring Data JPA Like or Containing


I'm messing with Spring Boot Data JPA and, reading the documentation, I got confused. Whats the difference?

What I understood is, the "Like" operator makes SQL without the "%" surrounding my String (where name like 'String') and the "Containing" operator makes SQL with the "%" surrounding my String (where name like '%String%'). Am I wrong?

I used the "Like" operator and he works fine in situations where the "%" is required in both sides so, I'm really confused!


Solution

  • It is correct that you can emulate a containing with a like.

    The differences are:

    • you have to enclose your search string with wildcards yourself when using like.
    • you can have wildcards not only at the beginning or end but also in the middle, multiple wildcards in the middle and different wildcards like _ which matches a single character.
    • a final subtile difference is that containing will escape wildcards contained in your search argument, which like would not. So when searching for abc%def the two behave differently
                      | containing     | like (with additional `%` around the searchstring)
      -------------------------------------------------------------------------------------
      123abc%def456   | matches        | matches
      123abcXYZdef456 | does not match | matches