【问题标题】:Escaping colons in hibernate createSQLQuery在休眠 createSQLQuery 中转义冒号
【发布时间】:2011-01-17 10:32:37
【问题描述】:

我对如何创建包含冒号的 SQL 语句感到困惑。我正在尝试创建一个视图并且我正在使用(注意双冒号):

create view MyView as (
  SELECT 
    tableA.colA as colA,
    tableB.colB as colB, 
    round(tableB.colD / 1024)::numeric, 2) as calcValue,
  FROM 
    tableA, tableB
  WHERE
    tableA.colC = 'someValue'
);

这是一个 postgres 查询,我不得不使用双冒号 (::) 才能正确运行该语句。

然后我通过上面的语句传递:

s.createSQLQuery(myQuery).executeUpdate();

我得到一个:

Exception in thread "main" org.hibernate.exception.DataException: \
    could not execute native bulk manipulation query
 at org.hibernate.exception.SQLStateConverter.convert(\
    SQLStateConverter.java:102)
    ... more stacktrace...

我的上述语句的输出更改为(注意问号):

create view MyView as (
  SELECT 
    tableA.colA as colA,
    tableB.colB as colB, 
    round(tableB.colD / 1024)?, 2) as calcValue,
  FROM 
    tableA, tableB
  WHERE
    tableA.colC = 'someValue'
);

显然,hibernate 将我的冒号与命名参数混淆了。

有没有办法转义冒号(谷歌建议提到单个冒号被转义为双冒号不起作用)或运行此语句的另一种方式?

谢谢。

【问题讨论】:

    标签: hibernate postgresql escaping


    【解决方案1】:

    executeUpdate() 方法不适用于作为 CREATE VIEW 的 DDL 语句,但适用于作为 UPDATE 的 DML 语句

    您应该获取一个普通的 JDBC 连接,可能来自 Sessions.connection() 并运行您的 SQL 语句。

    Connection connection = s.connection();
    Statment statment = connection .createStatement();
    try {
    statment .execute("CREATE VIEW ...");
    } finally {
     statment .close();
    }
    

    【讨论】:

    • 我想可以。但是有没有办法真正解析冒号(如果我足够固执并且想使用最初的方式?)
    • @Stratosgear 您可以使用 SQL 标准的 CAST 语法解决它,例如 CAST( round(tableB.colD / 1024) AS numeric )
    【解决方案2】:

    请参阅Hibernate Native Query problem with named parameters 以获得解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2011-02-03
      • 2012-08-06
      • 1970-01-01
      • 2013-01-30
      • 1970-01-01
      • 2019-04-12
      相关资源
      最近更新 更多