In my project I'm using Hibernate and write now I'm struggling with one issue. In the project which I'm working on, I need to create something like dynamic queries. Let me present what is going on...
I have 8 different queries. The SELECT, FROM and first WHERE clause is the same for each query:
SELECT col1, col2, ..., colX FROM table WHERE col1 = :param1;
The point is that based on one parameter the rest of the query is different in each case. Cases below:
- Simple query - just the base for the other queries.
- One more
WHEREcondition:AND col2 = :param2. - The same like in previous one, but condition on different column:
AND col3 = :param2. - More complex -
JOINclause, in theWHEREclause second condition again on different column, but also here we haveUNIONwith exactly the same query like in point 3. - The same like query no. 4, but with different column in
WHEREclause beforeUNIONstatement. - Same rule as in query 5.
- Same rule as in query 5.
- Here only
JOINand inWHEREclause are 3 conditions instead of 2.
I thought that's it, but I just remind that for all of these queries, we could apply dynamically extra WHERE conditions, but they need to appear in both SELECTs if there is a JOIN.
Does it even possible? Right now I solve the problem by passing correct columns names to the method with the StringBuilder and the if ... else statements, which takes care of UNION, JOIN and WHERE conditions.
I'm not proud of it, I don't like it, but I don't know how to resolve this problem better...
WHEREclauses depend? How do you handle it's value and can you show a code sample of what you did exactly, I think it will be more interesting to see it in the code.create or replace view view_over_table As select 'external_param_value1' as ext_value, col1, col2 from table where condition1 union select 'external_param_value2' as ext_value, col1, col2 from table where condition1 and condition2;. Then you would do:SELECT * FROM view_over_table where ext_value = :external_param_that_determines_the_logic;- Would that do ? By doing this you could hide the complexity behind the view ... which seems ok to me.JOINorUNIONor even both at the same time.JOINandUNION) and which columns should be in theWHEREcondition.