1

I'm new to JPA (JPQL), so I got stacked with no good solution to maintain WHERE clause with a flexible comparison plan. I would like to implement a JPQL statement of the form like:

SELECT i FROM Item i 
    WHERE i.weight (comparison_operator_placeholder) :weight
        AND i.height (comparison_operator_placeholder) :height;

(comparison_operator_placeholder):{ = | < | > | <= | >= }

The (comparison_operator_placeholder) shall be selected during runtime, based on user's input.
Intuitively I realize that no such grammar exists, however, there shall be other way than writing queries for each combination. I will appreciate any workaround.

univarn
  • 45
  • 6
  • Be careful: you mixup the concept of "wildcard" (typically `%`, `_` or maybe `*`) with comparison operators. This might be misleading and misunderstood by other programmers. What you're actually looking for is "dynamic", I guess. – MWiesner Mar 19 '16 at 15:32
  • Can you show us the Java code logic which would determine the type of comparison you intend to do in the `WHERE` clause? – Tim Biegeleisen Mar 19 '16 at 15:37
  • 1
    you're missing "<>" btw – Neil Stockton Mar 19 '16 at 18:13

1 Answers1

1

You don't have to write multiple queries. Just use a variable for the operator(s), like so:

String query = "SELECT i FROM Item i \n" +
                "WHERE i.weight " + operator + " :weight \n" +
                "AND i.height " + operator2 + " :height";
neal
  • 880
  • 6
  • 11
  • probably I was not very clear at description. Your solution is fine, but I was thinking about '@NamedQuery'. So I wanted to annotate an entity with a query like your, but it will not work in such case. – univarn Mar 19 '16 at 16:03
  • 1
    See this question: http://stackoverflow.com/questions/22167730/dynamic-named-query-in-entity-class-using-jpql-example – neal Mar 19 '16 at 16:06