According to PostgreSQL documentation section: 5.9.6. Caveats
Constraint exclusion only works when the query’s
WHEREclause contains
constants. A parametrized query will not be optimized, since the
planner cannot know which partitions the parameter value might select
at run time.
Is there any library that provide some sort of PreparedStatement(I mean only SQL injection facility since we could not benefit from optimized performance of PreparedStatement) and also generates a static SQL string so we could benefit from Constraint Exclusion feature?
You can configure the PostgreSQL JDBC driver to switch over to prepared statements after a certain number of invocations. See Connection to the Database the variable
prepareThresholdand also follow the link in that section.In your case you can either try the value
0or a very large number. I’m not sure whether0means “use prepared statements immediately” or “never use prepared statements”. A large number should prevent prepared statements for sure.Using this method, your Java-code still uses
PreparedStatementand the driver is responsible for proper quoting. The protocol between the driver and the server will use “unprepared” statements.