How to get around the use of reserved database words with Hibernate?

Asked

Viewed 52 times

1

I am learning to work with REST API in Java using spring with Hibernate and I have the following problem. My entity has the name user which is a reserved word in the database I’m using(postgres), so when I run the program I get the following error.

org.hibernate.tool.schema.spi.Commandacceptanceexception: Error executing DDL "create table user (id uuid not null, Birthday date, email varchar(60) not null, password varchar(50) not null, username varchar(30) not null, Primary key (id)", via JDBC Statement ... Caused by: org.postgresql.util.Psqlexception: ERROR: syntax error at or near "user"

Manually creating this table I can work around this problem using double quotes around the table name. There is a way to circumvent this error in creating my entity without changing the table name?

Follow the code of my entity:

@Entity(name = "user")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private UUID id;

  @Column(length = 30, unique = true, nullable = false)
  private String username;

  @Column(length = 60, unique = true, nullable = false)
  private String email;

  @Column(length = 50, nullable = false)
  private String password;

  @Column(nullable = true)
  private Date birthday;
}

1 answer

2


Solutions found in stackoverflowEn


In that reply: Postgres DDL error: 'syntax error at or near "user"' [Uplicate] is as follows:

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

because, can make the escape of keyword similarly in your entity statement.

Or in another answer: Unable to use table named "user" in postgresql Hibernate as follows:

@Table(name="`users`")

that is, it involves the name user with the sign of crase.


In your code something like this solves:

@Entity(name = "\"user\"")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private UUID id;

  @Column(length = 30, unique = true, nullable = false)
  private String username;

  @Column(length = 60, unique = true, nullable = false)
  private String email;

  @Column(length = 50, nullable = false)
  private String password;

  @Column(nullable = true)
  private Date birthday;
}

or

@Entity(name = "`user`")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private UUID id;

  @Column(length = 30, unique = true, nullable = false)
  private String username;

  @Column(length = 60, unique = true, nullable = false)
  private String email;

  @Column(length = 50, nullable = false)
  private String password;

  @Column(nullable = true)
  private Date birthday;
}

Other examples

Browser other questions tagged

You are not signed in. Login or sign up in order to post.