开发者

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 o开发者_如何学运维n/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.


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.


Use backtips. It is your way of telling Hibernate that you want that identifier to be quoted properly. It's just a coincidence that backticks are also used as quoting character for MySQL. This backtick will be translated to whatever is the quoting character for your database. Regarding adding quotes as the default behavior, I'm not sure Hibernate have such option. Nothing in the documentation mentions a possible option, and I don't remember seeing anything like this in the test suite as well. But I don't think it's a good idea, as "reserved keywords" are exceptions, not the rule.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜