0

Problem: I've a simple entity with id property, and I can't save it.

Exception:

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 ...

Code:

@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
VB_
  • 45,112
  • 42
  • 145
  • 293

2 Answers2

5

User is a reserved Keyword in many Databases.

You should not name your table like this.

Try:

@Entity
@Table(name = "MyUser")
public class User {
    @Id
    @GeneratedValue
    private long userId;
Angelo Fuchs
  • 9,825
  • 1
  • 35
  • 72
2

If you really want to use the User as a table name, you could write:

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

or if you use JPA 2.0, you can also escape like this:

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

The most safe way though is that you should use a non-reserved word as table name, as @Angelo wrote. Also, see this post for more details

Community
  • 1
  • 1
Sleeper9
  • 1,707
  • 1
  • 19
  • 26