Issue
Is there any possible to change date format in jdbcTemplate
. For example i have this code:
List<Map<String, Object>> items = jdbcTemplate.queryForList(sql)
and it reurn result something like this:
ChangedOn -> {LocalDateTime@13522} "2022-04-21T13:37:52"
CreatedOn -> {LocalDateTime@13524} "2022-04-19T12:24:26
Is there any possible to format to this LocalDateTime:
public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm";
Solution
I managed by myself, need just override one method in class ColumnMapRowMapper
:
public class MyColumnMapRowMapper extends ColumnMapRowMapper {
public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm";
@Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Map<String, Object> mapOfColumnValues = createColumnMap(columnCount);
for (int i = 1; i <= columnCount; i++) {
String column = JdbcUtils.lookupColumnName(rsmd, i);
Object columnValue = convertDate(getColumnValue(rs, i));
mapOfColumnValues.putIfAbsent(getColumnKey(column), columnValue);
}
return mapOfColumnValues;
}
private Object convertDate(final Object columnValue) {
if (columnValue != null && columnValue
.getClass()
.equals(LocalDateTime.class)) {
return ((LocalDateTime) columnValue).format(DateTimeFormatter.ofPattern(DATETIME_FORMAT));
} else {
return columnValue;
}
}
}
And then override one more method in the class JdbcTemplate
:
jdbcTemplate = new JdbcTemplate(dataSource) {
@Override
protected RowMapper<Map<String, Object>> getColumnMapRowMapper() {
return new MyColumnMapRowMapper();
}
};
Answered By - Aliaksandr Vysotskiy
Answer Checked By - Mary Flores (JavaFixing Volunteer)