有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SQLFunctionTemplate不应用查询参数的顺序

我将问题简化为以下简单模板:

//I extend the PostgreSQL dialect because I need a non-standard feature.
public class MyDialect extends PostgreSQL82Dialect {

  public MyDialect() {
    //With PostgreSQL, "date2 - date1" returns the number of days between the 2 given dates.
    registerFunction("date_diff", new SQLFunctionTemplate(StandardBasicTypes.LONG, " ((?2) - (?1)) "));
  }
}

在这个请求中,我注意到Hibernate并不关心((?2) - (?1))?之后的数字

因此,如果我使用:

Expression<Date> date1 = ...
Expression<Date> date2 = ...
em.getCriteriaBuilder().function("date_diff", Integer.class, date1, date2);

该调用将返回(date1 - date2)的结果,但我预期(date2 - date1)

它是一个bug还是一个特性?给参数赋值有什么意义


共 (1) 个答案

  1. # 1 楼答案

    我认为问题在于参数绑定。我在尝试向SQL Server注册DATE_ADD函数时遇到了类似的问题。这是我的方法调用:

    registerFunction("addminutes", new TestSqlFunctionTemplate(TimeMillisType.INSTANCE, "DATEADD(MINUTE, ?2, ?1)"));
    

    在深入研究source code for TemplateRenderer之后,我发现问题在于如何呈现SQL字符串。render函数被传递一个要发送的参数列表,但由于参数已绑定,它被发送一个“”列表指示绑定参数的字符串。在我的示例中,使用带有绑定参数的查询时,render函数的输出为:

    DATEADD(MINUTE, ?, ?)
    

    它没有给出订单的指示。我正在寻找另一种解决方案,但到目前为止我还没有遇到任何问题