17

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 ?

2 Answers 2

29

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 ...");
Sign up to request clarification or add additional context in comments.

5 Comments

Just tried it but it does not work. It says : ERROR: ORA-00911: caractère non valide
No, it's different. Before, it was Exception in thread "main" org.hibernate.QueryException: Not all named parameters have been set: [ltc", DOAATLTC", ltchnom"]
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.
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.
If you used a text block to write your query, this solution will not work since a \ that's not at the end of the line is not a valid escape character in text blocks. You's have to go with @rogerdpack's approach
8

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.