【问题标题】:How to call mysql date_format function in JPQL如何在 JPQL 中调用 mysql date_format 函数
【发布时间】:2014-05-31 04:41:54
【问题描述】:

我正在使用eclipseLink 2.4.1JPA 2.0.1 和其他支持工具开发网络服务。我创建了一个包含日期类型列的表。我想获取特定日期的记录。我正在使用 mysql 的 date_format 并收到以下错误:

java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 
Exception Description: Syntax error parsing[select o from Clients o  where FUNCTION('date_format',{o.effectiveStartDate},{d,'dd-mm-yyyy'})='27-05-2014']
[90, 111] The JDBC escape format does not start with either 'd', 't' or 'ts'.
[110, 110] The JDBC escape format is missing the close quote.

即使我尝试直接调用 date_format 为:

Select o from Clients o  where date_format(o.effectiveStartDate '%d-%m-%Y'})='27-05-2014'

然后我得到语法错误解析。 invalid token [(].

我也尝试了 namedQuery,但没有成功。

JPQL如何调用此类函数。

【问题讨论】:

  • 嗨,梅赫迪洛菲。感谢您的编辑并使其更具可读性。我是新手,我该如何进行这种格式化。

标签: mysql jakarta-ee jpa eclipselink


【解决方案1】:

“{o.effectiveStartDate}”试图做什么?删除大括号,否则它将尝试将其解释为 JDBC 转义语法日期(它不是)。

JPA 2.1 'FUNCTION' 语法将是

FUNCTION("date_format", o.effectiveStartDate, "the_date_format")

其中“the_date_format”与 MySQL 根据http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format 接受的第二个参数匹配

这当然需要您使用符合 JPA2.1 的实现;您的实现可能有一些其他特定于供应商的 FUNC 或其他不可移植的,我没有时间考虑什么时候有一个标准变体可以满足您的需要

【讨论】:

  • effectiveStartDate 是表中的一列,我想要它的值。你能给我举个例子,如何在 JPQL 中调用 date_format 函数吗??
  • 以简单格式尝试过,但出现错误,因此尝试使用 JDBC 对象。
  • 尝试如下:
    java.lang.IllegalArgumentException:在EntityManager中创建查询时发生异常:
    异常描述:语法错误解析[从客户端o选择o where o.effectiveStartDate ={d,'27-05-2014'} ]。
    [90, 105] JDBC 转义格式不以“d”、“t”或“ts”开头。
    在 org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1512)
  • FUNCTION 是 JPA 2.1 的一个特性。你似乎没有使用它。
  • 是的,是的。如果我在动态查询中调用 date_format,那么它会给出错误,如无效令牌 [(]。date_format 函数的示例链接?
猜你喜欢
  • 2018-01-05
  • 2016-04-13
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
  • 2015-10-21
  • 2013-08-10
  • 2012-12-15
  • 1970-01-01
相关资源
最近更新 更多