检查 jpql 查询中 java Timestamp 是否为 null

Check if java Timestamp is null in jpql query

我有以下代码:

    @Query("select t from Training t join t.skills s join t.trainers tr join t.discipline d  where " +
            "(t.name in :names or :names is null) and (s.name in :skills or :skills is null) and" +
            " (t.location = :location or :location is null) and " +
            " (d.name = :discipline or :discipline is null) and " +
            "(tr.firstName in :trainers or :trainers is null) and " +
            " (((:endDate > t.endDate) and (:startDate < t.startDate)) or (:startDate is empty))")
    public List<Training> filterTrainings(List<String> names, List<String> skills, String location,String discipline,List<String> trainers,Timestamp endDate,Timestamp startDate);

我需要检查 :startDate:endDate 是否为空。有办法吗?

我得到的错误是 nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

当尝试检查 :startDate is null 开始日期是时间戳时。

或许您可以使用 and COALESCE(field, default_value_for_datetime_field) 构建您的 SQL 查询。所以你不会得到 NULL 值。

您可以构建一个默认值作为当月、当周的开始,或者任何可以公平替代您的模型域的日期时间值。

您可以尝试将 LocalDateTime 作为参数而不是时间戳传递吗? java.sql.Timestamp 可能会导致您出现问题。您可以通过调用 timestamp.toLocalDateTime()

转换为 LocalDateTime

或者,您可以尝试将时间戳作为字符串传递给 filterTrainings。如果在调用 filterTrainings 方法之前时间戳为 null,则分配一个空字符串。 String _timestamp = timestamp == null ? "" : timestamp.toString()

然后,在您的 sql 语句中检查字符串是否为空.. ""=:timestamp OR function("to_timestamp", :timestamp, "yyyy-mm-dd hh:mm:ss.fffffffff")。这里的问题是我们正在使用 function 来访问本地数据库命令。