I've just checked JDBCTemplate and found out that all the queryFor...
method without params use Statement instead of PreparedStatement.
I think using PreparedStatement even if the query doesn't have any parameters still benefits if the query is being called multiple times.
So is there any way to use queryFor...
with PreparedStatement instead of Statement.
Comment From: sbrannen
Can you name a specific example (a specific method) where such a PreparedStatement
could be reused and what the benefit would be?
Comment From: cdxf
From the current JDBCTemplate:
@Override
public List<Map<String, Object>> queryForList(String sql) throws DataAccessException {
return query(sql, getColumnMapRowMapper());
}
This will call execute(StatementCallback<T> action, boolean closeResources)
which then create a Statement
.
But also the same method with args:
@Override
public List<Map<String, Object>> queryForList(String sql, @Nullable Object... args) throws DataAccessException {
return query(sql, args, getColumnMapRowMapper());
}
will call execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action, boolean closeResources)
instead.
I have a method which will query the database at intervals without any params. Using PreparedStatement instead of Statement may improve performance in this case because the DBMS will precompile the query instead of recompile it every time.
Comment From: jnizet
@cdxf I think that what Sam means is that creating a PreparedStatement
, executing it once, and then forgetting about it has no performance advantage over doing the same thing with a Statement
.
A PreparedStatement
is more efficient if you create the PreparedStatement
, then execute that PreparedStatement
several times in a loop with different parameters. But that won't happen if you call queryForList
several times: each time you call it, a new statement is created, so using a prepared statement instead of a statement wouldn't bring any advantage.
Comment From: cdxf
Thanks. I got it now. Hope the JDBCTemplate would provide a mechanism to reuse PreparedStatement instead of recreate it every time in the future