I need to use crosstab in my query. But the queries within crosstab also require filtering. Entire crosstab is dynamically constructed so I require someway to dynamically insert filters into the SQL inside crosstab.
Java Spring ignores all the named parameters inside string quotes. After a long search, I found the only way to achieve what I need is to use prepared statements to construct the inner SQL and then constructing the crosstab from them. Problem is the preparedStatemnts drain the connection pool and after 3-4 queries connection cannot be gotten anymore.
I also added custom implementation of namedJdbcTemplate to get access to the internal statement creator and connection.
try(
PreparedStatement statement1 = jdbcTemplate.getPreparedStatement("select * from table where 1=1 %s").formatted(filterString), Paramap);
PreparedStatement statement2 = jdbcTemplate.getPreparedStatement("select distinct name from table where 1=1 %s".formatted(filterString), ParamMap))
{
return """select * from crosstab($$%s$$, $$%s$$) as (%s)""".formatted(statement1.toString(), statement2.toString(), columndefinition);
}
After running few times I get "HikariPool-1 - Connection is not available, request times out after 30000ms.". It seems like the statements don't release their connections or something... I'm not sure.