7

I have just dabbled into using Querydsl, and am thoroughly enjoying the improvement it brings to interacting with JPA.

One remaining question I have is why do you have to wrap a like parameter with %?

Have I improperly configured something? Considering there is a method for starts/endsWith, I assumed like(str) would automatically wrap my str.

But to my surprise I needed to do this: "%" + str + "%" to get what I had expected.

Why is that? Is there a better way?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
TheNorthWes
  • 2,661
  • 19
  • 35
  • A random though would be how would it know whether to prefix and suffix with "%" or only suffix: or, for that matter only prefix. '%a%' 'a%' and '%a' are different queries? – Alan Hay Mar 03 '17 at 14:05
  • 3
    The QueryDSL `StringPath` class has `contains` and `containsIgnoreCase` method that automatically prepend and append the `%` symbol. – manish Mar 03 '17 at 22:46
  • According to [this](http://stackoverflow.com/a/5703687/703644) contains does a lot of different stuff. Is that not a correct reading? – TheNorthWes Mar 04 '17 at 02:35

2 Answers2

9

Yes, there is. (At least in QueryDSL 4.1.3), there is a contains(String s) method and variants of it (containsIgnoreCase etc.). This is what you are looking for.

JRA_TLL
  • 1,186
  • 12
  • 23
2

Like is there to do custom wildcard matching (the algorithm expect you to add the % characters by yourself and wherever you feel they are needed).

Apart from StartsWith / EndsWith which have implicit % characters.. there is Containing keyword which prepends and appends the % character. And this is what you are looking for here.

findByAttributeContaining(String charset);

Documentation example: spring jpa examples

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
  • I don't see `findByAttributeContaining` i do see the contains operation but based on [this](http://stackoverflow.com/a/5703687/703644) i though that was fundamentally different than starts & ends with – TheNorthWes Mar 02 '17 at 21:57
  • Check the example i added.. it clearly states: parameter bound wrapped in %. The Attribute in my example can be eny attribute that you want to match to the charset – Maciej Kowalski Mar 03 '17 at 09:37
  • This answer would seem to be talking about Spring Data derived queries and not QueryDsl, which was the subject of the original question. – Alan Hay Mar 03 '17 at 14:03