如何配置Hibernate以在表名周围加上引号

时间:2012-02-27 10:12:08

标签: hibernate postgresql grails gorm

我遇到过这种情况,我试图在Postgres中创建一个名为'user'的表,由于Hibernate没有将表名放在引号中而引发错误:

| Error 2012-02-27 23:06:58,782 [Thread-10] ERROR hbm2ddl.SchemaExport  - Unsuccessful: create table user (id int8 not null, version int8 not null, account_expired bool not null, account_locked bool not null, email_address varchar(255) not null, enabled bool not null, first_name varchar(255) not null, last_name varchar(255) not null, mobile_number varchar(255) not null, "password" varchar(255) not null, password_expired bool not null, username varchar(255) not null unique, primary key (id))

尽管指定它应该在DataSource.groovy中使用PostgreSQLDialect:

dialect = org.hibernate.dialect.PostgreSQLDialect

在处理Postgres时,如何配置Hibernate在表名周围加上引号?

3 个答案:

答案 0 :(得分:7)

您可以使用反引号在mapping块中引用表名。 Hibernate会根据Dialect:

将这些转换为数据库的引用方法
static mapping = {
    table "`user`"
}

您也可以将表重命名为不需要引用/转义的其他内容,例如。

static mapping = {
    table "users"
}

答案 1 :(得分:4)

这个答案可能会对您有所帮助:https://stackoverflow.com/a/3611916/947357 它显示了如何在Hibernate和JPA中引用表名。

答案 2 :(得分:1)

假设您正在学习与我相同的教程(InfoQ的“Grails入门”),您已经明白它没有为PostgreSQL提供任何报道。基于this post

  1. “用户”是Postgres中的保留字。
  2. 映射应该添加到类本身中(这不是很明显):
  3. class User { 
       String username 
       String password 
       ... 
       static mapping = { 
          table 'users' 
          password column: '`password`' 
       } 
    }
    

    class User { 
       String username 
       String password 
       ... 
       static mapping = { 
          table '`user`' 
          password column: '`password`' 
       } 
    }