赞
踩
1.去掉mybatis-plus.type-handlers-package=com.zcloud.sl.flood.model.handler.LocalDateTimeHandler
2.自定义时间转换器
- import org.apache.ibatis.type.BaseTypeHandler;
- import org.apache.ibatis.type.JdbcType;
- import org.springframework.stereotype.Component;
-
- import java.sql.*;
- import java.time.LocalDateTime;
- import java.time.ZoneId;
- import java.time.ZonedDateTime;
-
- /**
- * 不用注入容器,是因为在 MyBatis中,类型处理器是通过反射进行实例化的
- */
- public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {
-
- /**
- * 将 LocalDateTime 转换为中国时间(东八区),并设置到 PreparedStatement 中
- */
- @Override
- public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
- // 将 LocalDateTime 转换为 UTC 时间
- ZonedDateTime zonedDateTime = parameter.atZone(ZoneId.of("UTC"));
- // 将 UTC 时间转换为中国时间(东八区)
- ZonedDateTime cnZonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
- // 将 LocalDateTime 转换为 Timestamp,并设置到 PreparedStatement 中
- ps.setTimestamp(i, Timestamp.valueOf(cnZonedDateTime.toLocalDateTime()));
- }
-
- /**
- * 从 ResultSet 中获取 columnName 列对应的值,并将其转换为 LocalDateTime
- */
- @Override
- public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
- return getLocalDateTime(rs.getTimestamp(columnName));
- }
-
- /**
- * 从 ResultSet 中获取 columnIndex 列对应的值,并将其转换为 LocalDateTime
- */
- @Override
- public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
- return getLocalDateTime(rs.getTimestamp(columnIndex));
- }
-
- /**
- * 从 CallableStatement 中获取 columnIndex 列对应的值,并将其转换为 LocalDateTime
- */
- @Override
- public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
- return getLocalDateTime(cs.getTimestamp(columnIndex));
- }
-
- /**
- * 将 Timestamp 转换为 LocalDateTime
- */
- private LocalDateTime getLocalDateTime(Timestamp timestamp) {
- if (timestamp != null) {
- return timestamp.toLocalDateTime();
- }
- return null;
- }
- }
3.mybatisplus注册自定义转换器
- import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
- import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer;
- import com.zcloud.sl.flood.model.handler.LocalDateTimeHandler;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
-
- /**
- * 自定义 Mybatis 配置定制器,注入容器是因为要获取MybatisPlusProperties属性
- */
- @Configuration
- public class CustomMybatisConfigurationCustomizer implements MybatisPlusPropertiesCustomizer {
-
-
-
- @Override
- public void customize(MybatisPlusProperties properties) {
- // 注册自定义类型处理器
- properties.getConfiguration().getTypeHandlerRegistry().register(LocalDateTimeHandler.class);
- }
-
- @Bean
- public CustomMybatisConfigurationCustomizer mybatisConfigurationCustomizer() {
- return new CustomMybatisConfigurationCustomizer();
- }
- }
这样就解决问题了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。