我必须对我经常执行的数据库执行选择查询。它与普通语句一起工作完全正常:
List<Invoice> l = this.jdbcTemplate.query(
"SELECT id, name, stuff FROM example WHERE amount > ?",
new Object[] { "100" }, new RowMapper<Invoice>() {...} );
我经常执行上面的语句,所以出于性能原因我想使用准备好的语句。但是,我现在不确定如何正确使用 spring API 来实现这一点。
我很困惑为什么 spring 希望我提供一个 PreparedStatementCreator
的实例作为查询的参数?我认为这正是我在每次使用查询方法时不创建新的准备好的语句的意义所在。因此,我认为以下代码片段中的某些内容绝对毫无意义,因为每次我调用 query
-method 时都会新创建准备好的语句:
List<Invoice> l = this.jdbcTemplate.query(
new PreparedStatementCreator() {
String query = "SELECT id, name, stuff FROM example WHERE amount > ?";
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
return connection.prepareStatement(query);
}
},
new PreparedStatementSetter() {...},
new RowMapper<Invoice>() {...} );
我是否必须创建自己的 ReusablePreparedStatementCreator
?这只会在第一次调用 createPreparedStatement
时创建一个新方法。
PreparedStatementCreatorFactory
可以帮助我吗?
换句话说,我如何正确地创建一个选择查询,它使用带有 Spring JDBCTemplate 的准备好的语句来真正获得性能优势而不失去 RowMapper 的优势?
最佳答案
首先,我不确定不每次都重新创建准备好的语句是否会显着提高性能,因为 JDBC 驱动程序/数据库经常缓存准备好的语句。
但是如果你想用一个准备好的语句执行多个查询,只需使用 execute()
之一JdbcTemplate 的方法,它从 SQL 查询创建准备好的语句(或让您创建它),然后以准备好的语句作为参数执行回调。您可以在此回调中循环,并根据需要多次执行该语句。
关于java - 如何在 Spring JDBCTemplate 中正确使用准备好的语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23910354/