使用 Spring 创建 MySQL 表休眠
我们遇到了以下情况。
请注意,我知道保留字不应该用于表名,但我还是出于好奇才问这个问题。
我们正在使用 Spring + Hibernate管理我们的数据库。我正在向名为 Group 的数据库添加一个新模型。所以,我将我的模型定义为:
@Entity
@Table(name = "group")
public class Group {
...
}
现在,问题是,在重新创建表时,生成的 SQL 如下所示:
create table group (...)
不幸的是,这在 MySQL 中是不允许的,因为 group
是保留字。正确的SQL应该是:
create table `group`(...)
我有什么办法可以做到这一点吗?
We came across the following situation.
Please note that I know reserved words should not be used for table names, but I'm asking the question anyway out of curiosity more than anything.
We are using Spring + Hibernate to manage our database. I am adding a new model to the database called Group. So, I define my model as:
@Entity
@Table(name = "group")
public class Group {
...
}
Now, the problem is, when recreating the tables, the SQL that gets generated looks as follows:
create table group (...)
This unfortunately is not allowed in MySQL since group
is a reserved word. The correct SQL should be:
create table `group`(...)
Is there any way for me to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过执行以下操作强制 Hibernate 转义标识符:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-quotedidentifiers
基本上,你可以自己引用它们,然后Hibernate会使用适当的根据方言引用技巧
You can force Hibernate to escape identifiers by doing this:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-quotedidentifiers
Basically, you can quote them yourself, and then Hibernate will use the appropriate quoting technique according to the dialect
您可以尝试实现自己的 org.hibernate.cfg.NamingStrategy,它将反引号添加到所有表中。 -- 但我确信这滥用了 NamingStrategy 类。
You could try to implement your own org.hibernate.cfg.NamingStrategy, which add the backticks to all tables. -- But I am sure that this abuse the NamingStrategy class.