如何使用 Java 和 spring/hibernate 在我的数据库中正确插入日期(在我的数据库中获取错误的时间)?

How to correctly insert a date in my database using Java with spring/hibernate (getting wrong hours in my db)?

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

当我尝试在我的 spring 应用程序中使用存储过程时 select 来自数据库的一些日期(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();
    }

是的,当我从我的应用程序中插入这些值时,开始日期是 2019-03-30 11:00:00,结束日期是 2019-03-30 11:30:00 在我的数据库中。有人知道吗?

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

感谢 akuma8!