Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: use backticks for MySQL but not for HSQL

A project I work on (which uses Java, Spring, Hibernate) recently changed from Oracle to MySQL. There are a few cases where some of the properties in the code are reserved words in MySQL, such as "release".

There are a few solutions, 1) rename properties in the code and subsequent getter/setter methods, also update code that invokes those methods 2) annotate the property in the code with @Column(name="`release`"). This tells hibernate to quote the name when talking to the database.

I'd prefer to stay away from the first approach to reduce the chance of breaking more stuff. The second approach is "ok", except it becomes MySQL specific. In our dev. setup we use HSQL which doesn't like the backticks around those column names.

I looked at the org.hibernate.mapping.Column class and I see it has "getQuotedName" methods that I could potentially override if I could subclass Column and tell Hibernate to use my own Column class.

What's the best way to resolve this issue based on the preferred approach of a) not having to refactor the codebase (b/c of changing property names, getter/setter methods, etc) and b) wanting the app to still work in HSQL and MySQL.

It would be reasonable to have a property in properties file that could be toggled to switch on/off some Column naming fix. Which reminds me, I tried using a custom naming strategy and overriding the "columnName" method to surround the column name in backticks...this doesn't work, even on MySQL.

like image 823
codecraig Avatar asked Jan 12 '11 11:01

codecraig


1 Answers

The back ticks solution sounds good. But if it does not work or you do not want to use an undocumented feature of an specific JPA providery: Why don't use column names that are not reserved in any(or the most common) databases at all.

You don't need to change the name of your java properties, you must only specify a column name for them.

like image 99
Ralph Avatar answered Sep 19 '22 09:09

Ralph