Hibernate:奇怪的例外

时间:2014-04-09 10:11:59

标签: java sql hibernate

问题:我有一个带id属性的简单实体,我无法保存。

例外:

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    at ...
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "User"
  Position: 13
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2103)
    at ...

代码:

@Entity
@Table(name = "User")
public class User {
    @Id
    @GeneratedValue
    private long userId;

    //getter & setter

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        User user = new User();
        session.persist(user);
        session.getTransaction().commit();
        session.close();
    }
}

HQL:

Hibernate: create table User (userId int8 not null, primary key (userId))
Hibernate: create sequence hibernate_sequence
INFO: HHH000230: Schema export complete
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into User (userId) values (?)
WARN: SQL Error: 0, SQLState: 42601
ERROR: ERROR: syntax error at or near "User"
  Position: 13

2 个答案:

答案 0 :(得分:5)

用户是许多数据库中的保留关键字。

你不应该这样命名你的桌子。

尝试:

@Entity
@Table(name = "MyUser")
public class User {
    @Id
    @GeneratedValue
    private long userId;

答案 1 :(得分:2)

如果您确实想将用户用作表名,可以写:

@Entity
@Table(name = "`User`")
public class User {
    @Id
    @GeneratedValue
    private long userId;

或者如果你使用JPA 2.0,你也可以像这样逃避:

@Entity
@Table(name = "\"User\"")
public class User {
    @Id
    @GeneratedValue
    private long userId;

最安全的方法是你应该使用非保留字作为表名,如@Angelo所写。 另请参阅this post了解更多详情