Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify the timezone when inserting or updating a row with timestamp in Spring JDBC Template?

In JDBC API, I can simply set UTC timezone using the following

For inserting or updating

PreparedStatement myPreparedStatement = ...
myPreparedStatement.setTimestamp( 1, myDateTime, Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ));

For querying

ResultSet rs = ...
rs.next();
rs.getTimestamp( 1,  Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ) )

Using Spring JDBC Template, I will need to use something like this to query.

For querying, I don't have any issues because ResultSet is accessible via RowMapper and use the ResultSet to pass on the Calendar instance in UTC. However, for inserting or updating, I only have the following.

NamedParameterJdbcTemplate namedParameterJdbcTemplate = ....
SqlParameterSource parameters = new MapSqlParameterSource().addValue("current_timestamp", myDateTime )
namedParameterJdbcTemplate.update(sql, parameters);

Question

Is there a way to tell the Spring JDBC template to use my specified TimeZone?

I do not prefer to use the TimeZone.setDefault(..) because that's going to affect our legacy modules.

like image 660
gkeenley Avatar asked Nov 02 '26 02:11

gkeenley


1 Answers

You can use any method of JdbcTemplate which takes PreparedStatementCreator or PreparedStatementSetter as a parameter and set the field's meta information on those objects.

like image 124
gkeenley Avatar answered Feb 25 '26 01:02

gkeenley