LocalDateTimeHandler.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.backendsys.config.Mybatis.handler.timezone;
  2. import org.apache.ibatis.type.BaseTypeHandler;
  3. import org.apache.ibatis.type.JdbcType;
  4. import org.apache.ibatis.type.MappedJdbcTypes;
  5. import org.apache.ibatis.type.MappedTypes;
  6. import org.springframework.stereotype.Component;
  7. import java.sql.*;
  8. import java.time.LocalDateTime;
  9. import java.time.ZoneId;
  10. @MappedTypes(LocalDateTime.class)
  11. @MappedJdbcTypes(JdbcType.TIMESTAMP)
  12. @Component
  13. public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {
  14. @Override
  15. public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
  16. ps.setTimestamp(i, java.sql.Timestamp.valueOf(parameter));
  17. }
  18. @Override
  19. public void setParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
  20. if (parameter == null) {
  21. // 允许数据库使用默认值
  22. ps.setNull(i, Types.TIMESTAMP);
  23. } else {
  24. super.setParameter(ps, i, parameter, jdbcType);
  25. }
  26. }
  27. @Override
  28. public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
  29. java.sql.Timestamp timestamp = rs.getTimestamp(columnName);
  30. return convertToLocalDateTime(timestamp);
  31. }
  32. @Override
  33. public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
  34. java.sql.Timestamp timestamp = rs.getTimestamp(columnIndex);
  35. return convertToLocalDateTime(timestamp);
  36. }
  37. @Override
  38. public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
  39. java.sql.Timestamp timestamp = cs.getTimestamp(columnIndex);
  40. return convertToLocalDateTime(timestamp);
  41. }
  42. /**
  43. * 设置时区(如果为空则默认使用上海时区)
  44. */
  45. private LocalDateTime convertToLocalDateTime(java.sql.Timestamp timestamp) {
  46. if (timestamp == null) return null;
  47. return timestamp.toInstant()
  48. .atZone(ZoneId.of("UTC"))
  49. .withZoneSameInstant(ZoneId.of(TimezoneContextHolder.getTimeZone()))
  50. .toLocalDateTime();
  51. }
  52. }