【问题标题】:JPA query not producing same results for equivalent MySQL queryJPA 查询不会为等效的 MySQL 查询产生相同的结果
【发布时间】:2020-11-10 03:52:32
【问题描述】:

我正在使用 MySQL 方言从事 SpringBoot 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 10:00:00]

[3, “test@example.com” , 2020-11-24 10:00: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 10:00:00]

[3,test@example.com,2020-11-24 10:00: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 10:00:00]

[3, “test@example.com” , 2020-11-24 10:00:00]

这不是我所期望的。我减去 8 小时,因为存储在数据库中的数据似乎以 UTC 时间存储,这在我的应用程序逻辑之后回滚了 8 小时,这使得它等同于 mySQL 查询。有谁知道这里有什么问题以及如何获得我的预期输出?

【问题讨论】:

    标签: java mysql spring-boot jpa


    【解决方案1】:

    你可以尝试实例化一个日历,在这种情况下,我认为你可以从时区中抽象出来,传递一个特定的日期,如下所示:

    //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);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多