【问题标题】:Hibernate return 0 record when using with @DateTimeFormat annotation使用 @DateTimeFormat 注释时休眠返回 0 记录
【发布时间】:2019-05-13 18:55:10
【问题描述】:

我在尝试向 UI 显示数据时遇到问题。

当我在 MySQL 中使用此查询从我的表中获取 Datetime 日期时。它确实返回了我想要的记录

select flight0_.id as id1_0_, flight0_.arrival_city as arrival_2_0_, flight0_.date_of_departure as date_of_3_0_, flight0_.departure_city as departur4_0_, flight0_.estimated_departure_time as estimate5_0_, flight0_.flight_number as flight_n6_0_, flight0_.operating_airlines as operatin7_0_ from flight flight0_ where flight0_.departure_city='AUS' and flight0_.arrival_city='NYC' and flight0_.date_of_departure='02-05-2018'

这是结果:

但是当我使用 Spring 将相同的数据输入到表单并提交时,没有任何返回。我使用的输入是一样的。

这是结果:

我在我的控制器类中指定了@DateTimeFormat注解,使用的模式与数据库中显示的相同,即“yyyy-MM-dd”

@RequestMapping("findFlights")
    public String findFlights(@RequestParam("from") String from, @RequestParam("to") String to,
            @RequestParam("departureDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date departureDate,
            ModelMap modelMap) {
        List<Flight> flights = repository.findFlights(from, to , departureDate);
        modelMap.addAttribute("flights", flights);
    
        return "displayFlights";
    }

这是我的存储库类:

public interface FlightRepository extends JpaRepository<Flight, Long> {
    @Query("select f from Flight f where f.departureCity=:departureCity and f.arrivalCity=:arrivalCity and f.dateOfDeparture=:dateOfDeparture")
    List<Flight> findFlights(@Param("departureCity") String from, @Param("arrivalCity") String to, @Param("dateOfDeparture") Date departureDate);
}

为了测试,我尝试删除该注释并停止从该列查询,它按预期工作。所以我很确定 @DateTimeFormat 注释根本不起作用。或者它可以工作,但不知何故 Hibernate 不理解我定义的模式。

我也试过输入屏幕上显示的值,是 2018-02-05 08:00:00.0 但没有运气。

有人可以给我任何想法吗?请帮忙!

【问题讨论】:

    标签: java spring hibernate jpa datetime-format


    【解决方案1】:

    谢谢, 我自己想通了。 我目前在马来西亚吉隆坡工作。所以默认的 'UTC' 时区与 MySQL 日期时间格式不匹配。 (仍然使用系统时间)。 我在 application.properties 中进行了更改

    spring.datasource.url=jdbc:mysql://localhost:3306/reservation?useLegacyDatetimeCode=false&serverTimezone=Asia/Kuala_Lumpur
    

    现在一切正常。

    【讨论】:

      【解决方案2】:

      您在 MySQL 查询中写入 flight0_.date_of_departure='02-05-2018'。但是输入表单中的2018-02-05 和Controller 方法中的pattern = "yyyy-MM-dd"。如果这个方法得到2018-02-05,那么它“认为” 02 是一个月。

      我认为日期格式 yyyy-MM-dd 和 yyyy-dd-MM 存在问题。此外,我们正在谈论美国航空公司:)

      1 - 尝试在调试器中查看日期的值。

      2 - 尝试明确的日期,例如 2017-12-20,也许您会看到异常。

      3 - 在您的查询中尝试f.dateOfDeparture&gt;=:dateOfDeparture(可能是时间问题,而不是日期问题)。

      【讨论】:

        猜你喜欢
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 2012-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多