|
@@ -0,0 +1,61 @@
|
|
|
+package com.backendsys.config.Mybatis.handler.timezone;
|
|
|
+
|
|
|
+import org.apache.ibatis.type.BaseTypeHandler;
|
|
|
+import org.apache.ibatis.type.JdbcType;
|
|
|
+import org.apache.ibatis.type.MappedJdbcTypes;
|
|
|
+import org.apache.ibatis.type.MappedTypes;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import java.sql.*;
|
|
|
+import java.time.LocalDateTime;
|
|
|
+import java.time.ZoneId;
|
|
|
+
|
|
|
+@MappedTypes(LocalDateTime.class)
|
|
|
+@MappedJdbcTypes(JdbcType.TIMESTAMP)
|
|
|
+@Component
|
|
|
+public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
|
|
|
+ ps.setTimestamp(i, java.sql.Timestamp.valueOf(parameter));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void setParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
|
|
|
+ if (parameter == null) {
|
|
|
+ // 允许数据库使用默认值
|
|
|
+ ps.setNull(i, Types.TIMESTAMP);
|
|
|
+ } else {
|
|
|
+ super.setParameter(ps, i, parameter, jdbcType);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
|
|
+ java.sql.Timestamp timestamp = rs.getTimestamp(columnName);
|
|
|
+ return convertToLocalDateTime(timestamp);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
|
|
+ java.sql.Timestamp timestamp = rs.getTimestamp(columnIndex);
|
|
|
+ return convertToLocalDateTime(timestamp);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
|
|
+ java.sql.Timestamp timestamp = cs.getTimestamp(columnIndex);
|
|
|
+ return convertToLocalDateTime(timestamp);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 设置时区(如果为空则默认使用上海时区)
|
|
|
+ */
|
|
|
+ private LocalDateTime convertToLocalDateTime(java.sql.Timestamp timestamp) {
|
|
|
+ if (timestamp == null) return null;
|
|
|
+ return timestamp.toInstant()
|
|
|
+ .atZone(ZoneId.of("UTC"))
|
|
|
+ .withZoneSameInstant(ZoneId.of(TimezoneContextHolder.getTimeZone()))
|
|
|
+ .toLocalDateTime();
|
|
|
+ }
|
|
|
+}
|