1

When using spring JdbcTemplate with prepared statements we can either set values of the parameters individually or just pass an array of objects.

jdbctemplate.update(sql, arg1, arg2);

or

jdbctemplate.update(sql, new Object[]{arg1, arg2});

Both of the methods are working. But I want to know how jdbctemplate knows to cast the data to match with the type of the database column when passed as an Object array.

And is there a performance difference in two methods?

How can I log the final query executed on the database. Enabling DEBUG logs for org.springframework.jdbc package didn't work for me.

Dulaj Atapattu
  • 448
  • 6
  • 23

1 Answers1

3

There is no difference between the two calls to JdbcTemplate.update, In Fact both of your calls go to the same method. There is only one update method in JdbcTemplate

Which has the following signature

public int update(String sql, Object... args) throws DataAccessException 

As you can see the last argument is a Java Variable Argument (...) not an Array. So you can either give individual values or an Object array to the same Variable Argument.

For your question of How JdbcTemplate knows to cast the data to match with the destination data type, It just creates a PreparedStatement and calls PreparedStatement.set*** methods based with the Order of Submitted Variable Arguments and value and actually only checks whether the given values are of String, Date or Calendar and calls PreparedStatement.setString or PreparedStatement.setTimestamp. For everything else just PreparedStatement.setObject

shazin
  • 21,379
  • 3
  • 54
  • 71
  • Thank you very much for the detailed answer. Can you give a solution to my last question regarding logging also? – Dulaj Atapattu Nov 04 '16 at 13:41
  • To log the query and parameters, set org.springframework.jdbc.core logging level to TRACE. If you're using spring-boot, then setting the property logging.level.org.springframework.jdbc.core=TRACE may be sufficient. – allenru Feb 08 '19 at 03:51