I tried simple program to test org.apache.tomcat.jdbc.pool.interceptor.StatementCache of tomcat jdbc pool as given in doc:(https://tomcat.apache.org/tomcat-9.0-doc/jdbc-pool.html#org.apache.tomcat.jdbc.pool.interceptor.StatementCache)
Code:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolConfiguration;
import org.apache.tomcat.jdbc.pool.PoolProperties;
public class TestPreparedstmtCache {
public static void main(String[] args) {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setUrl("jdbc:postgresql://localhost:5432/mydb");
poolProperties.setUsername("myuser");
poolProperties.setPassword("mypass");
poolProperties.setDriverClassName("org.postgresql.Driver");
poolProperties.setJdbcInterceptors("StatementCache(max=500)");
DataSource dataSource = new DataSource();
dataSource.setPoolProperties(poolProperties);
try (Connection connection = dataSource.getConnection()) {
PoolConfiguration poolConfig = dataSource.getPoolProperties();
// Check if prepared statements are being cached
// Create and execute prepared statement 1
PreparedStatement pstmt1 = connection.prepareStatement("select count(*) from mytable");
ResultSet rs=pstmt1.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1));
}
int hashcode1 = pstmt1.hashCode();
System.out.println("Hashcode of pstmt1: " + hashcode1);
// Create and execute prepared statement 2 with the same query
PreparedStatement pstmt2 = connection.prepareStatement("select count(*) from mytable");
ResultSet r2=pstmt2.executeQuery();
while(r2.next()){
System.out.println(r2.getInt(1));
}
int hashcode2 = pstmt2.hashCode();
System.out.println("Hashcode of pstmt2: " + hashcode2);
if (hashcode1 == hashcode2) {
System.out.println("Statement caching worked. Same hashcode for pstmt1 and pstmt2.");
} else {
System.out.println("Statement caching did not work. Different hashcodes for pstmt1 and pstmt2.");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
when I tried this one it always returns the hash code is different and i checked connection object while debugging it has preparedstatementcache property with value.
so am I missing anything here, how can i verify preparedStatment is cached correctly.