CherryHill
CherryHill

Reputation: 11

(Spring JPA) Method name query

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.

Upvotes: 0

Views: 245

Answers (1)

Jetto Mart&#237;nez
Jetto Mart&#237;nez

Reputation: 999

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.

Upvotes: 1

Related Questions