如何在Hibernate中的本机SQL查询中转义冒号`:`?

时间:2015-08-18 15:15:32

标签: java sql hibernate

我有一个看起来像这样的原生SQL查询:

Query query = session.createSQLQuery("SELECT
        XMLSERIALIZE
        (CONTENT
          XMLELEMENT
          (
            NAME \"ltc:DOAATLTC\",
            XMLATTRIBUTES
            (
              'http://www.edftrading.com/Trade/Common/DoaatLTC' AS \"xmlns:ltc\",
              'http://www.edftrading.com/Trade/Common/DoaatLTCHourlyNomination' AS \"xmlns:ltchnom\"
            ),
            XMLELEMENT ( ... ) FROM ...");

问题在于Hibernate将:DOAATLTC\",:ltc\",:ltchnom\",解释为参数,并期望我们提供值query.setString("DOAATLTC\",", ...)query.setString("ltc\",", ...),{{1} }

但是我不希望Hibernate这样解释,所以我想逃避冒号query.setString("ltchnom\",", ...)

怎么做?

2 个答案:

答案 0 :(得分:9)

在Hibernate中,转义是通过\前置完成的。但在Java中,您还必须通过另一个\转义\。因此,每个:都需要由\\:替换。最后,你得到:

Query query = session.createSQLQuery("SELECT
    XMLSERIALIZE
    (CONTENT
      XMLELEMENT
      (
        NAME \"ltc\\:DOAATLTC\",
        XMLATTRIBUTES
        (
          'http://www.edftrading.com/Trade/Common/DoaatLTC' AS \"xmlns\\:ltc\",
          'http://www.edftrading.com/Trade/Common/DoaatLTCHourlyNomination' AS \"xmlns\\:ltchnom\"
        ),
        XMLELEMENT ( ... ) FROM ...");

答案 1 :(得分:0)

如果冒号是.inner之类的类型转换,则可以将其重写为SELECT reltuples::BIGINT以避免冒号。

ref