简体   繁体   中英

How to use a prepared statement correctly with Spring JDBCTemplate?

I have to do a select query on a database which I will execute often. It works completely fine with a normal statement:

 List<Invoice> l = this.jdbcTemplate.query(
                     "SELECT id, name, stuff FROM example WHERE amount > ?",
                     new Object[] { "100" }, new RowMapper<Invoice>() {...} );

I execute the above statement very frequently, so for performance reason I want to use a prepared statement. However I'm now unsure how I correctly would use the spring API to achieve this.

I'm confused why spring would like me to give an instance of a PreparedStatementCreator as an argument for query? I thought that it's exactly the point that I do not create a new prepared statement every time I use the query method. So I think something along the line of the following snippet would be absolutely pointless as the prepared statement is created newly every time I call the 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>() {...} );

Do I have to create my own ReusablePreparedStatementCreator ? Which would only create a new method on the first call of createPreparedStatement .

Could the PreparedStatementCreatorFactory help me?

So to rephrase, how would I correctly create a select query that uses a prepared statement with Spring JDBCTemplate to really gain a performance advantage without losing the advantage of the RowMapper?

First of all, I'm not sure you would get a significant performance increase by not recreating the prepared statement every time, because the JDBC driver/database often caches prepared statements.

But if you want to execute multiple queries with a single prepared statement, simply use one of the execute() methods of JdbcTemplate, which creates a prepared statement from a SQL query (or lets you create it), and then executes a callback taking the prepared statement as argument. You can loop inside this callback, and execute the statement as many times you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM