0

First of all, sorry for my poor english.

I want to change the following query to 'findBy~' method, but i don't know how to.

@Query(value = "SELECT t FROM Table t WHERE (b.num1 <= :variable or b.num1 IS NULL) AND (b.num2 >= :variable or b.num2 IS NULL)")

Or, is it impossible to get the result by using 'findby~' method name? I would appreciate if anyone could reply.

1 Answers1

1

Spring Data JPA does have support for all the conditions in your query and nesting of conditions. I'd argue that your query name will become unnecesarelly verbose. It would end up as

Table findByNum1LessThanEqualOrNum1IsNullAndNum2GreaterThanEqualOrNum2IsNull(Integer var0, Integer var1);

This should return the appropiate query, but you'd need to send the variable twice, once for each equals.

With @Query you have the freedom to call your query as you'd like and reuse the same variable.

Now, you CAN fix the downsides of using named methods by using a default method like

default Table myQuery (Integer var) {
    return findByNum1LessThanEqualOrNum1IsNullAndNum2GreaterThanEqualOrNum2IsNull(var, var);
}

So you call this instead of the actual query, but then again, it would be much cleaner to use @Query with a proper, descriptive or even self-documenting name if you don't comment your code (you should comment your code). In any case, I suggest you use method names for simple queries and use @Query for anything more complex.

Please, refer to the following links for further reading:

Spring JPA Query Creation

Spring JPA Query Keyword Repository

LeafyJava article on Query Precedence Tricks, which also provides and example of how to change your query logic in case the conditions aren't arranged as you want.

This SO question also provides a bit of insight.

Jetto Martínez
  • 917
  • 7
  • 17
  • So Thank you for the answer ! I've tried by your method name, but inappropriate results returned. The query is like '~ where num1 <= ? OR num1 is null AND num2 >= ? OR num2 is null'. They are not enclosed with '()' so too many records returned. – CherryHill Jul 09 '21 at 01:30
  • Yes, I was afraid of that happening. JPA encloses conditions reading for right to left as I understand, but I haven't found proper documentation of it. In the third and fourth link I provided there is an alternative method that changes the logic of the query to get the same results (logical equivalence). That's the only alternative I know of but i've haven't used it because of the name the methods ends with. – Jetto Martínez Jul 09 '21 at 14:38