java - 从mysql休眠的spring boot中的日期检索问题
问题描述
我是 Spring Boot 的新手,从数据库中检索日期时遇到了一个问题。我已经以 UTC 格式存储了日期,但是当我尝试检索日期时,它会再次以 UTC 格式转换日期。我想要一个我存储的日期。
例如,假设欧洲/柏林时间是 2018-09-27 09:25:00,UTC 时间是 2018-09-27 07:25:00 那么当我插入数据时,它将日期和时间存储为 2018-09- 27 07:25:00 但是当我检索它时,Instant
它将再次以 UTC 转换时间,所以我得到的日期为 2018-09-27T05:25:00Z
2018-09-27 12:34:40.525 TRACE LAPTOP-A64OROCI---o.h.t.d.s.BasicExtractor : extracted value ([created_2_0_] : [TIMESTAMP]) - [2018-09-27T05:25:00Z]
在属性下面,我在 application.properties 中添加了
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false spring.jackson.time-zone=UTC
我在 pom.xml 中添加了以下依赖项
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
下面是我的应用程序类
@SpringBootApplication
// Spring application base class
@EntityScan(basePackageClasses = { WiseLabApiApplication.class, Jsr310JpaConverters.class })
// Specify global exception handler from base package
@ControllerAdvice(basePackageClasses = WiseLabApiApplication.class)
public class WiseLabApiApplication extends SpringBootServletInitializer {
/**
* Set the UTC time zone
*/
@PostConstruct
void init() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
/**
* Override configure method for deployment war file
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(WiseLabApiApplication.class);
}
/**
* Starting point of WiseLab Server
*
* @param args
*/
public static void main(String[] args) {
Environment environment = SpringApplication.run(WiseLabApiApplication.class, args).getEnvironment();
String serverEnvironment = null;
String[] activeProfiles = null;
String serverPort = environment.getProperty("server.port");
if (!Objects.isNull(environment)) {
activeProfiles = environment.getActiveProfiles();
if (activeProfiles.length != 0) {
serverEnvironment = activeProfiles[0];
logger.info(
"\n\n*****************Server Configuration************************************************************");
logger.info("WiseLabAPI server started ");
logger.info("Environment Mode => " + serverEnvironment.toUpperCase());
logger.info("Server Port => " + serverPort);
logger.info(
"\n\n*************************************************************************************************");
}
}
}
}
下面是我的 AuditingConfig 类
@Configuration
@EnableMBeanExport(registration=RegistrationPolicy.IGNORE_EXISTING)
@EnableJpaAuditing
public class AuditingConfig {
@Bean
public AuditorAware<Long> auditorProvider() {
return new SpringSecurityAuditAwareImpl();
}
}
class SpringSecurityAuditAwareImpl implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null ||
!authentication.isAuthenticated() ||
authentication instanceof AnonymousAuthenticationToken) {
return Optional.empty();
}
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
return Optional.ofNullable(userPrincipal.getId());
}
}
下面是我的基础审计类,我在我的模型中扩展了基础审计类
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public abstract class BaseEntity {
private static final long serialVersionUID = 6783352876165714983L;
@CreatedDate
@Column(name = "created_at")
private Instant createdAt;
@LastModifiedDate
@Column(name = "updated_at")
private Instant updatedAt;
@Column(name = "deleted", columnDefinition = "boolean default false")
private boolean deleted = false;
public BaseEntity() {
}
public Instant getCreatedAt() {
System.out.println("Date in getCreatedAt : ");
System.out.println(createdAt);
return createdAt;
}
public Instant getUpdatedAt() {
return updatedAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
public void setUpdatedAt(Instant updatedAt) {
this.updatedAt = updatedAt;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}
下面是我扩展 BaseEntity 的主模型类
@Entity
@Table(name = "admin_group_master")
@SQLDelete(sql = "UPDATE admin_group_master SET deleted = true WHERE id = ?")
@Loader(namedQuery = "findAdminGroupMasterById")
@NamedQuery(name = "findAdminGroupMasterById", query = "SELECT grp FROM AdminGroupMaster grp WHERE grp.id = ? AND grp.deleted = false")
@Where(clause = "deleted = false")
@DynamicUpdate
public class AdminGroupMaster extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = -6667484763475502316L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@NotBlank
@Column(name = "name")
private String name;
}
下面是 adminGroupMaster 存储库类
@Repository
@Transactional(readOnly = true)
public interface AdminGroupMasterRepository extends JpaRepository<AdminGroupMaster, Long> {
List<AdminGroupMaster> findByCreateByCustomer(Customer customer);
}
下面是我的服务类
@Service
public class AdminGroupService {
public BaseResponse<GroupListResponse> getAdminGroupDetails(UserPrincipal currentAdmin) throws CustomException {
// Get all admin groups based on customer id
List<AdminGroupMaster> adminGroupDetails = adminGroupMasterRepository
.findByCreateByCustomer(currentAdmin.getCustomer());
adminGroupDetails.stream().forEach((groupDetails) -> {
System.out.println("Created Date Time : ");
System.out.println( groupDetails.getCreatedAt());
});
}
}
任何帮助都会得到帮助。
提前致谢。
解决方案
--- 确保 db 的时区是 UTC
- 检查您的 application.properties,确保将useLegacyDatetimeCode=false&serverTimezone=UTC添加到您的 mysql url。
jdbc:mysql://localhost:3306/dbname?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC
- 将以下内容添加到 application.properties
spring.jpa.properties.hibernate.jdbc.time_zone = UTC
--- 确保您的服务器的时区是 UTC
- 需要以下内容:
@PostConstruct
void init() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
推荐阅读
- android - 如何在前台发送推送通知
- ios - 像在 spotify 中一样创建过渡和动画
- php - PHP 数组 - 排序
- c - C - 循环条件为 ptr 时的分段错误!= NULL
- python-3.x - 如何掩盖热图的某些单元格?
- haxe - Haxe + Openfl 不起作用找不到类型:HelloWorld
- node.js - 如何仅使用 ASAR 文件手动构建 Electron 应用程序?
- java - 在 ec2 实例上部署 Java maven 项目
- c++ - 在 Qt Widgets Application 中,重载的 `paintEvent` 中的 `setValue` 后无法更改 `QSpinBox` 的值?
- node.js - 在 node.js 中使用 request-promise 将外部 api 数据打印到控制台时出错