当前位置: 首页 > 知识库问答 >
问题:

从mysql冬眠的Spring启动中的日期检索问题

廖鸿达
2023-03-14

我是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]

在属性下面,我在应用程序中添加了。属性

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=falsespring.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*************************************************************************************************");
        }
    }
}

}

下面是我的海选配置课程

@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());
                });
    }
}

感谢您的帮助。

提前谢谢。

共有1个答案

公良照
2023-03-14

---确保db的时区为UTC

  1. 检查你的application.properties,确保你添加useLegacyDatetimeCode=false
jdbc:mysql://localhost:3306/dbname?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.jpa.properties.hibernate.jdbc.time_zone = UTC

---确保服务器的时区为UTC

  1. 需要做到以下几点:
@PostConstruct
void init() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
 类似资料:
  • 本文向大家介绍从具有日期值的列中检索单个MySQL查询中的MIN和MAX日期,包括了从具有日期值的列中检索单个MySQL查询中的MIN和MAX日期的使用技巧和注意事项,需要的朋友参考一下 为此,您可以使用聚合函数和。让我们首先创建一个表- 使用插入命令在表中插入一些记录- 使用select语句显示表中的所有记录- 这将产生以下输出- 以下是在单个查询中检索MIN和MAX日期的查询- 这将产生以下输

  • 问题内容: 全部, 我有一个带有称为时间戳记的列的MYSQL表。它的数据类型为“ 10/1/2009 3:25:08 PM”,“ 10/1/2009 3:30:05 PM”,“ 10/4/2009 3:40:01 PM”,等等.. 我想编写一个SQL查询来选择在两个日期之间出现的时间戳字段中的所有值。 userInput日期将没有时间部分。您能为此建议正确的MySQL查询语法吗?谢谢 问题答案:

  • 我是Spring MVC和HiberNate的新手,我的会话配置有问题。我是通过使用Hibernate来做到这一点的。我现在想做的是将在DAO中自动装配会话工厂。 这是应用程序上下文。xml - 这是完整的堆栈跟踪。 这是刀的代码 购物车控制器

  • 另一种方法是使用Crieteria关联,但关联只能与和一起工作! 请在这里帮帮我。

  • 我知道@recestParam注释用于将查询字符串的参数值绑定到控制器方法参数。例如,http://localhost:8080/reservations?date=2017-01-01.然而,值=“日期”来自哪里?我没有看到任何值"日期"在我的html页面。

  • 问题内容: 休眠是否对选择查询有支持? 有没有一种方法可以为该查询创建休眠条件? 问题答案: 由于这里存在所有“怀疑”和“猜测”,因此当我偶然发现此问题时,我肯定会回答: 否,Hibernate不支持DISTINCT ON查询。 在Hibernate 4.3.9-final下测试