12

I have a native SQL query that looks like that :

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 ...");

The thing is that Hibernate interprets :DOAATLTC\", , :ltc\", , :ltchnom\", as parameters and expects that we give values query.setString("DOAATLTC\",", ...) , query.setString("ltc\",", ...) , query.setString("ltchnom\",", ...)

But I do not want Hibernate to interpret like that, so I want to escape the colon :.

How to do that ?

Tunaki
  • 125,519
  • 44
  • 317
  • 399
hydertza
  • 153
  • 1
  • 1
  • 10

2 Answers2

21

In Hibernate, escaping is done with prepending by \. But in Java, you also have to escape \ by another \. So every : needs to be replaced by \\:. Finally, you get:

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 ...");
Tunaki
  • 125,519
  • 44
  • 317
  • 399
  • Just tried it but it does not work. It says : `ERROR: ORA-00911: caractère non valide` – hydertza Aug 18 '15 at 15:36
  • No, it's different. Before, it was `Exception in thread "main" org.hibernate.QueryException: Not all named parameters have been set: [ltc", DOAATLTC", ltchnom"]` – hydertza Aug 18 '15 at 15:49
  • Wait, after thinking a bit. You are certainly right and this error message `ERROR: ORA-00911: caractère non valide` must be a new error message as the precedent `Exception in thread "main" org.hibernate.QueryException: Not all named parameters have been set: [ltc", DOAATLTC", ltchnom"]` has been solved by your solution. – hydertza Aug 18 '15 at 16:03
  • Well, I fixed the second Error message that had anything to do with the problem of that question. So, I can guarantee that your solution works fine. – hydertza Aug 18 '15 at 16:10
3

If your colon is a cast like SELECT reltuples::BIGINT then you can rewrite it as a cast(reltuples as BIGINT) to avoid the colons.

ref

rogerdpack
  • 56,766
  • 33
  • 241
  • 361