我是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 =否 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());
});
}
}
需要任何帮助。
谢谢。
答案 0 :(得分:0)
---确保数据库的时区为UTC
jdbc:mysql://localhost:3306/dbname?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.jpa.properties.hibernate.jdbc.time_zone = UTC
---确保服务器的时区为UTC
@PostConstruct
void init() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}