oracle mybatis resultMap 返回时间格式化 String 转String 如2023-04-06 15:14:45.424 转成2023-04-06 15:14:45
时间: 2024-05-28 10:09:07 浏览: 181
Mybatis resultMap
可以使用MyBatis的TypeHandler来进行时间格式化转换,具体可以参考以下代码:
1.在MyBatis配置文件中注册TypeHandler:
<typeHandlers>
<typeHandler handler="com.example.MyDateTypeHandler"/>
</typeHandlers>
2.编写自定义TypeHandler类:
public class MyDateTypeHandler extends BaseTypeHandler<String> {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
try {
Date date = sdf.parse(parameter);
ps.setTimestamp(i, new java.sql.Timestamp(date.getTime()));
} catch (ParseException e) {
throw new SQLException("Error converting String to Timestamp");
}
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnName);
if (timestamp != null) {
return sdf.format(new Date(timestamp.getTime()));
}
return null;
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnIndex);
if (timestamp != null) {
return sdf.format(new Date(timestamp.getTime()));
}
return null;
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Timestamp timestamp = cs.getTimestamp(columnIndex);
if (timestamp != null) {
return sdf.format(new Date(timestamp.getTime()));
}
return null;
}
}
这样,在MyBatis的结果映射文件中,使用resultMap时,就可以直接将时间格式化成字符串了。
阅读全文