JDBC internalssenior8+ years
A service prepares the identical SQL text on every request — a fresh PreparedStatement object each time — executes it once, and closes it. Does this ever get pgjdbc's server-side plan-reuse benefit, and what would need to change?
Not from this pattern alone. pgjdbc's default policy tracks how many times a specific PreparedStatement object has been executed and only promotes it to a genuine server-side prepared statement (a real PREPARE sent to PostgreSQL, holding a compiled plan for the session) after that object crosses a threshold — five executions by default. A fresh object created and discarded on every request never gets past one execution, so it stays in emulated mode forever, even though the SQL text is character-for-character identical every time — the driver isn't tracking "have I seen this text before", it's tracking "has this Java object specifically been run enough times".
PreviousHow does a PreparedStatement's plan cache actually save work compared to concatenated SQL, and what's the trade-off — parameter sniffing — that comes with it?Next Why does JDBC batching speed up a bulk insert, and what's the difference between plain addBatch()/executeBatch() and a driver's rewriteBatchedInserts setting?