【问题标题】:How to correctly insert a date in my database using Java with spring/hibernate (getting wrong hours in my db)?如何使用带有 spring/hibernate 的 Java 在我的数据库中正确插入日期(在我的数据库中获取错误的时间)?
【发布时间】:2020-02-19 19:51:43
【问题描述】:

所以最近我一直在我的项目中使用 Calendar 和 Date 数据类型,并且在向我的数据库(使用 Spring 和 Hibernate/MySql5Dialect)插入(和检索)正确的小时数时遇到问题。

当我尝试在我的 spring 应用程序中使用一个存储过程,它会从数据库中选择一些日期(DATETIME 数据类型)时,Java 中返回的对象总是比我的数据库中的实际日期早一小时(例如,2019-03 -30 09:00:00 在我的数据库中,我得到 2019-03-30 08:00:00 从我的服务返回)。现在,当我在 mysql workbench 中调用相同的程序时,它可以完美运行。

现在我注意到,当我尝试从我的 Spring 应用程序中插入带有日期的记录时,例如 2019-03-30 09:00:00,我在我的数据库中得到 2019-03-30 08:00:00 ,这是我插入日期的方式:

private PatientAppointmentDTOR createPatientAppointmentDTOR() {
        PatientAppointmentDTOR dtor = factory.manufacturePojo(PatientAppointmentDTOR.class);
        dtor.setCpId(5L); // foreign keys...
        dtor.setBranchId(2L);
        dtor.setPtId(32L);
        dtor.setEmployeeId(55L);
        dtor.setInDepartmentId(7L);
        dtor.setPatientAppointmentStatusId(20L);
        Calendar cal1 = Calendar.getInstance();
        cal1.set(Calendar.YEAR, 2019);
        cal1.set(Calendar.MONTH, 2);
        cal1.set(Calendar.DAY_OF_MONTH,30);
        cal1.set(Calendar.HOUR_OF_DAY, 12);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);
        Date start = cal1.getTime();
        Calendar cal2 = Calendar.getInstance();
        cal2.set(Calendar.YEAR, 2019);
        cal2.set(Calendar.MONTH, 2);
        cal2.set(Calendar.DAY_OF_MONTH,30);
        cal2.set(Calendar.HOUR_OF_DAY, 12);
        cal2.set(Calendar.MINUTE, 30);
        cal2.set(Calendar.SECOND, 0);
        cal2.set(Calendar.MILLISECOND, 0);
        Date end = cal2.getTime();
        dtor.setStartTime(start);
        dtor.setEndTime(end);
        Company company = companyService.getEntityById(5L);
        GroupDTOS gdtos = groupService.getDTOById(2L);
        when(auth.userDetails())
         .thenReturn(EntityFactory
         .createUserDetails(DBStaticFields.Role.CLINIC_ADMIN, company, gdtos, factory));
        return dtor;
    }

然后我只是使用这个 JUnit 测试将它插入到我的数据库中:

    @Test
    @DisplayName("test insertion")
    void testInsert() {
        PatientAppointmentDTOR dtor = this.createPatientAppointmentDTOR();
        PatientAppointmentDTOS dtos = patientAppointmentService.insert(dtor);
        assertThat(dtos).isNotNull();
        assertThat(dtos.getId()).isNotNull();
    }

是的,当我从我的应用程序中插入这些值时,我的数据库中的 startDate 是 2019-03-30 11:00:00,endDate 是 2019-03-30 11:30:00。有人知道吗?

【问题讨论】:

  • 检查时区:​​您的应用程序 + 数据库服务器

标签: mysql spring hibernate datetime calendar


【解决方案1】:

正如 akuma8 所指出的,问题出在我的应用程序属性中设置的时区。如果有人遇到类似问题,只需在应用程序属性中设置正确的时区 "&serverTimezone=$$$" 即可连接到数据库,现在一切都正确匹配了。

谢谢akuma8!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2020-04-08
    • 2018-08-23
    相关资源
    最近更新 更多