我在使用SpringBoot方言的MySQL JPA后端项目中工作。在我的数据库中,有id,creator_identifier,date的Conference记录,在JPA实体中,date被建模为LocalDateTime。我在数据库中有以下记录。
1,“test@example.com”,2020年-11-10: 00:00:00
2,“test@example.com”,2020年-11- 10:00:00
3,“test@example.com”,2020年-11-24 10:00
当我在MySQL控制台中执行以下查询时,
SELECT c.id, c.creator_identifier, c.date FROM Conference c WHERE c.date > '2020-11-10 03:00:00' AND c.creator_identifier = 'test@example.com' ORDER BY c.date我会得到
2,test@example.com,2020-11- 10 :00:00
3,test@example.com,2020-11-24 10:00
这是我的预期产出。
但是,当我在Repository类中执行JPA查询时,当参数由Logic类传入时,我会在系统时间11点运行它。
方法在ConferenceLogic.java中的应用
public List<Conference> findByRecentDate(UserI userInfo) {
LocalDateTime adjustedTime = LocalDateTime.now().minusHours(8);
List<Conference> queryResult = conferenceRepository.findByRecentDate(userInfo.getUserEmail(), adjustedTime);
//Some other logic
}方法在ConferenceRepository.java中的应用
public interface ConferenceRepository extends JpaRepository<Conference, Long> {
@Query("SELECT c.id, c.creatorIdentifier, c.date FROM Conference c WHERE c.date > ?2 AND c.creatorIdentifier = ?1 ORDER BY c.date")
List<Conference> findByRecentDate(String email, LocalDateTime adjustedTime);
}我会得到以下结果
1,“test@example.com”,2020年-11-10: 00:00:00
2,“test@example.com”,2020年-11- 10:00:00
3,“test@example.com”,2020年-11-24 10:00
这不是我所期望的。我减去8小时,因为存储在数据库中的数据似乎存储在UTC时间,这回滚回我的应用程序逻辑后面8h,这使得它等同于mySQL查询。有谁知道这里的问题是什么,以及如何获得我的预期输出?
发布于 2020-11-11 08:53:23
您可以尝试实例化日历,在本例中,我认为您可以从时区抽象出来,以传递特定日期,如下所示:
//Initialice with current date
Calendar c = Calendar.getInstance();
//Substract hours
c.add(Calendar.HOUR, -hoursToSubtract);
//To get Date object use c.getTime();在您的存储库方法中:
public interface ConferenceRepository extends JpaRepository<Conference, Long> {
@Query("SELECT c.id, c.creatorIdentifier, c.date FROM Conference c WHERE c.date > ?2 AND c.creatorIdentifier = ?1 ORDER BY c.date")
List<Conference> findByRecentDate(String email, Date adjustedTime);
}https://stackoverflow.com/questions/64762615
复制相似问题