[英]How to change date format in jdbcTemplate
Is there any possible to change date format in jdbcTemplate
.是否可以更改
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:有没有可能格式化为这个 LocalDateTime:
public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm";
I managed by myself, need just override one method in class ColumnMapRowMapper
:我自己管理,只需要覆盖 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
:然后覆盖 class
JdbcTemplate
中的另一种方法:
jdbcTemplate = new JdbcTemplate(dataSource) {
@Override
protected RowMapper<Map<String, Object>> getColumnMapRowMapper() {
return new MyColumnMapRowMapper();
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.