How to use prepared statement using Spring JDBCTemplate?

I need to make a select query in the database, which I will execute frequently. This works 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 perform the above statement very often, so for performance reasons, I want to use a prepared statement. However, I am now not sure how to properly use the spring API for this.

I am confused why spring would like me to provide an instance PreparedStatementCreatoras an argument to the request? I thought that was just the way I did not create a new prepared statement every time I used the query method. Therefore, I think that something along the line of the next fragment will be completely meaningless, since the prepared statement is created every time I call the- querymethod:

 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>() {...} );

Should I create my own ReusablePreparedStatementCreator? This would create a new method on the first call createPreparedStatement.

Can it PreparedStatementCreatorFactoryhelp 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 benefits of RowMapper?

+4
1

, , , , JDBC/ .

, execute() JdbcTemplate, SQL- ( ), , . , .

+4

Source: https://habr.com/ru/post/1542321/


All Articles