0

I am trying to figure out how to use a like with a named query in JPA / Spring 4. So far I have the following...

@NamedQuery(name = "MyClass.listItems",
  query = "SELECT DISTINCT(a.name) FROM MyClass a where a.name like ?1")

The problem is I need the % at the end and I am not sure how to add it. I tried like ?1% but this gives a compile error.

Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
Jackie
  • 21,969
  • 32
  • 147
  • 289

1 Answers1

1

Ok so I found something that works, kind of...

@NamedQuery(name = "MyClass.listItems",
        query = "SELECT DISTINCT(a.name) FROM MyClass a where a.name like CONCAT(?1, '%')")

Problem here is it only works if after (which is fine in my case). I think you could chain a Concat if you wanted to but haven't tried yet.

Community
  • 1
  • 1
Jackie
  • 21,969
  • 32
  • 147
  • 289
  • 1
    That's basically right and not a Spring related issue actually. JPQL doesn't support `%` in like expressions inside the query. The `%`es have to be applied to the value bound to the parameter. The Spring Data JPA adds some additional capabilities to that (see the [reference documentation](http://docs.spring.io/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.at-query) for more details). – Oliver Drotbohm Jul 08 '14 at 15:09