【问题标题】:extract year, mounth and day from a date using eclipselink jql使用eclipselink jql从日期中提取年、月和日
【发布时间】:2017-03-10 15:13:22
【问题描述】:

我正在将 primefaces 日历中的日期发送到支持 bean。 primefaces 发送的对象是日期。

<p:calendar id="exact_Date" value="#{h.model.arhExactDate}" pattern="yyyy/MM/dd"/>

调试器中的日期看起来像 Thu Mar 02 00:00:00 EET 2017。

我只想从中提取日期部分(没有时间)并将其与数据库中的时间戳进行比较like 2017-03-02 18:57:19.152 使用 eclipselink jpql。 p>

所以它会是这样的: cast(2017-03-02 18:57:19.152 as varchar) like 2017-03-02 18 其中“like”后面的部分是从日期开始的日期。

看着这个basic eclipselink guide,我发现我可以使用如下提取方法:extract(year from my_date)。但是我怎样才能提取所有我需要的东西呢?

我尝试了下面的查询,但不是一个有效的表达式:

select e from MyEntity e where  extract(year from e.reqDate) = :extract(year from exactDate)

如果它有效,我希望有类似的东西:

 extract(year,mounth,day from e.reqDate) =:(exactDate)

我不想要这样的东西: extract(year from e.reqDate) = :extract(year from exactDate) and extract(month from e.reqDate) = :extract(month from exactDate) and extract(day from e.reqDate) = :extract(day from exactDate)

【问题讨论】:

  • eclipseLink 指南将格式显示为“EXTRACT(YEAR, e.startDate)”。你的好像不一样。您是否尝试过“从 MyEntity e where extract(YEAR, e.reqDate) = :year_parameter”中选择 e?什么是错误或生成的 SQL?

标签: jpa eclipselink jpql


【解决方案1】:

由于您想传入一个日期对象并且只比较不包括时间部分的日期值,您可以尝试在 JPQL 中使用 TruncateDate 或 Trunc 选项:

"select e from MyEntity e where truncateDate(e.reqDate) = :dateParameter"

TRUNC 存在于大多数数据库中,如果没有给出年/月/日参数,则应默认去除时间。可以使用 JPQL 的 FUNCTION 在其他提供者中访问它:

"select e from MyEntity e where FUNCTION('TRUNC', e.reqDate) = :dateParameter"

【讨论】:

    【解决方案2】:

    我希望 EclipseLink 支持以下供应商扩展 JPQL 功能

    MONTH(field)
    YEAR(field)
    DAY(field)
    

    请注意,这些不是 JPA 标准,但大多数 JPA 提供者都支持它们。检查您的提供商的手册。 "extract" 只是一个 SQL 函数,只能在极少数数据库上的 SQL 中工作,所以最好避免

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 2017-10-28
      • 1970-01-01
      • 2016-07-27
      • 2015-01-12
      • 2021-10-02
      • 2018-02-16
      • 2019-03-20
      相关资源
      最近更新 更多