Hibernate:对MySQL使用反引号,但对HSQL不使用反引号 [英] Hibernate: use backticks for MySQL but not for HSQL

查看:477
本文介绍了Hibernate:对MySQL使用反引号,但对HSQL不使用反引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个项目(使用Java,Spring,Hibernate)最近从Oracle改为MySQL。有几种情况,代码中的一些属性是MySQL中的保留字,例如release。

有几个解决方案,1)重命名属性在代码和后续的getter / setter方法中,还会更新调用这些方法的代码2)使用@Column在代码中注释属性(name =`release)。这告诉hibernate在与数据库交谈时引用该名称。



我宁愿远离第一种方法来减少破坏更多东西的机会。第二种方法是好的,除了它变成MySQL特定的。在我们的开发中。设置我们使用HSQL,它不喜欢这些列名称周围的反引号。



我查看了org.hibernate.mapping.Column类,我发现它有getQuotedName 我可能会覆盖的方法,如果我可以继承Column并告诉Hibernate使用我自己的Column类。

解决此问题的最佳方法是基于以下方法:a)不必重构代码库(更改属性名称的B / C,getter / setter方法等等)和b)希望应用程序仍然可以在HSQL和MySQL中工作。



在属性文件中有一个属性可以切换到打开状态是合理的/关闭某些列命名修补程序。这提醒了我,我尝试使用自定义命名策略,并重写columnName方法以反引号括住列名称...即使在MySQL上也不行。

解决方案

back ticks解决方案听起来不错。但是,如果它不起作用,或者您不想使用特定JPA提供程序的未记录功能:为什么不使用未在任何(或最常见)数据库中保留的列名称。



您不需要更改java属性的名称,只能为它们指定一个列名称。


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.

解决方案

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.

这篇关于Hibernate:对MySQL使用反引号,但对HSQL不使用反引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆