How spring JdbcTemplate recognizes data types?

2019-08-02 02:52发布

问题:

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.

回答1:

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