2012-02-27 30 views
4

我有一种情况,我试图在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)) 

尽管这是指定它应该使用PostgreSQLDialect在DataSource.groovy中:在Postgres打交道时

dialect = org.hibernate.dialect.PostgreSQLDialect 

我如何配置Hibernate把周围的表名引号?

+2

我会强烈建议使用不同的表名。使用保留字将会给你带来问题,而不仅仅是在Hibernate中。 – 2012-02-27 10:13:26

回答

7

您可以用反引号引用mapping块中的表名。 Hibernate会转换那些无论报价方法是基于方言数据库:

static mapping = { 
    table "`user`" 
} 

您也可以只表重命名为别的东西,不要求报价/转义,例如

static mapping = { 
    table "users" 
} 
1

假设你follwing相同的教程和我一样(“Grails的入门”由InfoQ)你已经明白它不提供任何覆盖到PostgreSQL。基于this post

  1. “用户”是Postgres中的保留字。
  2. 该映射将被添加到类本身(这不是绝对明显):
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`' 
    } 
}