springboot mybatis LocalDateTime 全局配置时间转换问题
时间: 2023-10-14 20:08:00 浏览: 76
在Spring Boot应用程序中使用MyBatis时,可以使用TypeHandler来解决LocalDateTime类型的全局配置时间转换问题。
首先,创建一个实现了TypeHandler接口的类,例如:LocalDateTimeTypeHandler。
```
public class LocalDateTimeTypeHandler implements TypeHandler<LocalDateTime> {
@Override
public void setParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
if (parameter != null) {
ps.setTimestamp(i, Timestamp.valueOf(parameter));
} else {
ps.setNull(i, Types.TIMESTAMP);
}
}
@Override
public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnName);
return getLocalDateTime(timestamp);
}
@Override
public LocalDateTime getResult(ResultSet rs, int columnIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnIndex);
return getLocalDateTime(timestamp);
}
@Override
public LocalDateTime getResult(CallableStatement cs, int columnIndex) throws SQLException {
Timestamp timestamp = cs.getTimestamp(columnIndex);
return getLocalDateTime(timestamp);
}
private LocalDateTime getLocalDateTime(Timestamp timestamp) {
if (timestamp != null) {
return timestamp.toLocalDateTime();
}
return null;
}
}
```
然后,在MyBatis的配置文件中将该TypeHandler注册为全局TypeHandler。
```
<configuration>
<typeHandlers>
<typeHandler handler="com.example.LocalDateTimeTypeHandler"/>
</typeHandlers>
</configuration>
```
这样,在使用LocalDateTime类型的时候,MyBatis就会自动调用该TypeHandler进行转换。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)