I recently encounter this kind of problematic requirement: making a native SQL in hibernate dynamic. The query should be written as a template. And based on the user selection, a concrete SQl statement is derived.
It’s pointless to have this conversation if we use HQL’s query criteria of course. But with native SQL code, I admit there is no easy/legitimate way around but hack.
Technology stack: Hibernate with JPA through Srping JpaTemplate helper.
So for example, suppose this is what my SQL template looks like
Hibernate Native SQL
123456
<sql-queryname="findProductCoverageSummaryForSelectedUserInTeam"resultset-ref="productCoverageResult"> select
product_id_level_${level},
product_name_level_${level}
from product
</sql-query>
This is what the coressponding Java code looks like
I use the native query just as a placeholder for my sql template. Then I use Apache StringUtils to replace those variables with the actual values.
I can’t think of another better way to do it!
If you need a more complicated template, ones with logical condition then use Velocity as the templating engine. Velocity is what I am using but FreeMarker also is a good
candidate.
Native SQL with Velocity template
1234567
<sql-queryname="findProduct"resultset-ref="productCoverageResult"> select
product_id_level_$level,
product_name_level_$level
from
product #if ($orderBy) order by $orderBy $sortType #end
</sql-query>