The example shown above requires the programmer to use
PostgreSQL™ specific code in a
supposedly portable API which is not ideal. Also it sets the
threshold only for that particular statement which is some extra
typing if we wanted to use that threshold for every statement.
Let's take a look at the other ways to set the threshold to enable
server side prepared statements. There is already a hierarchy in
place above a PreparedStatement
, the
Connection
it was created from, and above that
the source of the connection be it a Datasource
or a URL. The server side prepared statement
threshold can be set at any of these levels such that the value
will be the default for all of it's children.
// pg extension interfaces org.postgresql.PGConnection pgconn; org.postgresql.PGStatement pgstmt; // set a prepared statement threshold for connections created from this url String url = "jdbc:postgresql://localhost:5432/test?prepareThreshold=3"; // see that the connection has picked up the correct threshold from the url Connection conn = DriverManager.getConnection(url,"test",""); pgconn = (org.postgresql.PGConnection)conn; System.out.println(pgconn.getPrepareThreshold()); // Should be 3 // see that the statement has picked up the correct threshold from the connection PreparedStatement pstmt = conn.prepareStatement("SELECT ?"); pgstmt = (org.postgresql.PGStatement)pstmt; System.out.println(pgstmt.getPrepareThreshold()); // Should be 3 // change the connection's threshold and ensure that new statements pick it up pgconn.setPrepareThreshold(5); PreparedStatement pstmt = conn.prepareStatement("SELECT ?"); pgstmt = (org.postgresql.PGStatement)pstmt; System.out.println(pgstmt.getPrepareThreshold()); // Should be 5