How to escape names in Hibernate

There are situations where you might need either your entity or a property of your entity to have a specific name. Unfortunately, there are cases where hibernate generates SQL statements containing syntax errors. For example if the column/table name has a reserved keyword as value you will probably experience an SQLGrammarException.

A solution to this is the usage of a delimited identifier. The definition of a delimited identifier is defined in section 2.13 of the JPA specification. You just need enclose the name ( either the table name or the column or any annotation that allows you to define a database identifier ) in double quotes.

e.g.


	@ManyToOne
	@JoinColumn(name = "\"user\"", nullable = false)
	private User user;


Unfortunately, the above technique does not apply to the Hibernate Envers framework ( at least till the version 5.3.9.Final ). So in case you need to audit the entity with the Hibernate Envers there is a Hibernate configuration property that applies to both frameworks.

This property is named : hibernate.globally_quoted_identifiers which indicates whether all database identifiers should be quoted.

There are also other related properties like hibernate.auto_quote_keyword that specifies whether to automatically quote any names that are deemed keywords.

You can check the reference for more details

e.g.


<property name="hibernate.auto_quote_keyword" value="true"/>

References
https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/appendices/Configurations.html