Lui
Lui

Reputation: 774

Dynamic queries in Hibernate

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:

  1. Simple query - just the base for the other queries.
  2. One more WHERE condition: AND col2 = :param2.
  3. The same like in previous one, but condition on different column: AND col3 = :param2.
  4. More complex - 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.
  5. The same like query no. 4, but with different column in WHERE clause before UNION statement.
  6. Same rule as in query 5.
  7. Same rule as in query 5.
  8. Here only 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 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...

Upvotes: 0

Views: 13955

Answers (1)

Vitalii Muzalevskyi
Vitalii Muzalevskyi

Reputation: 662

I think Criteria API of Hibernate should help you with this. Some examples: http://www.baeldung.com/hibernate-criteria-queries

Upvotes: 1

Related Questions