Search code examples
javamysqlhibernatehibernate-criteria

Workaround for java hibernate to update row in mySQL tables with reserved words as column names


I need to connect to a legacy database with tables that have column names such as 'like'. Most logical way to fix this was to rename the columns, but the db admin does not want to perform any changes to the existing db.

Is there a way to workaround this to force hibernate to add backtick?


Solution

  • There are various workarounds, depending on the context:

    • For XML mapping files, enclose the keyword with quotes1.

    • For Hibernate annotations, enclose the keyword with quotes2.

    • You can tell Hibernate to quote all SQL identifiers with:

      hibernate.globally_quoted_identifiers=true
      

      in the Hibernate settings file.

    • In HQL, you can escape aliases via a custom transformer; see https://stackoverflow.com/a/5754720/139985 for an example.

    References:


    1 - Different sources say to use database-specific quotes or backticks which Hibernate supposedly knows how to translate. I am not in a position to check this. Both approaches could work.

    2 - Apparently double quotes (escaped) and square brackets can be used.