Reputation: 774
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:
WHERE
condition: AND col2 = :param2
.AND col3 = :param2
.JOIN
clause, in the WHERE
clause second condition again on different column, but also here we have UNION
with exactly the same query like in point 3.WHERE
clause before UNION
statement.JOIN
and in WHERE
clause 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 SELECT
s 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...
Upvotes: 0
Views: 13955
Reputation: 662
I think Criteria API of Hibernate should help you with this. Some examples: http://www.baeldung.com/hibernate-criteria-queries
Upvotes: 1