Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate saving User model to Postgres

Tags:

I'm using Postgres via Hibernate (annotations), but it seems to be falling over dealing with a User object:

12:09:16,442 ERROR [SchemaExport] Unsuccessful: create table User (id  bigserial not null, password varchar(255), username varchar(255), primary key (id)) 12:09:16,442 ERROR [SchemaExport] ERROR: syntax error at or near "User" 

If I run the SQL manually I have to put quotes around the table name as user seems to be a postgres keyword, but how can I convince hibernate to do this itself?

Thanks in advance.

like image 429
rich Avatar asked Aug 31 '10 11:08

rich


People also ask

Can Hibernate be used with Postgres?

PostgreSQL supports a set proprietary data type which Hibernate doesn't map by default. Popular examples for that are the JSON and JSONB data types which allow you to persist and query JSON documents in a PostgreSQL database. If you want to use these types with Hibernate, you need to define the mapping yourself.


2 Answers

You need to escape the table name when using reserved keywords. In JPA 1.0, there is no standardized way and the Hibernate specific solution is to use backticks:

@Entity @Table(name="`User`") public class User {     ... } 

In JPA 2.0, the standardized syntax looks like this:

@Entity @Table(name="\"User\"") public class User {     ... } 

References

  • Hibernate Core documentation
    • 5.4. SQL quoted identifiers
  • JPA 2.0 specification
    • 2.13 Naming of Database Objects
like image 106
Pascal Thivent Avatar answered Sep 27 '22 22:09

Pascal Thivent


User is a key word, find a better name or use quotes: "User". (bad idea imho, but it works if you do it everywhere)

like image 30
Frank Heikens Avatar answered Sep 27 '22 21:09

Frank Heikens