Postgresql Hibernate Id Generation Strategy

Asked

Viewed 2,045 times

3

I have a system in JEE7 with Hibernate and Postgresql database, the tables are with auto ID generation by Hibernate:

@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

What happens is that Hibernate generates a unique index for all tables, for example, an id=657 for Client and the next id=658 for Product, .....

How it would be possible to generate an index, automatically, for each table?

Thank you.

2 answers

4

Alternatively it is also possible to use a column of the type SERIAL combined with a generation strategy IDENTITY from the Hibernate side.

@Id
@Column(name = "meu_id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
  • This way Hibernate will "take care of everything", create the field and auto increment? I will not need to create a Sequence in Postgresql?

  • 1

    Actually Postgre will take care of everything. The guy serial is equivalent to the use of a sequence (but much more succinct).

2

I think the best way is for you to create the quence for each table in the database and then set in the model to use it:

To create Quence, use:

CREATE SEQUENCE seq_empresa START 1;

To tell Hibernate to use this Quence:

@Id
@Column(name = "id_empresa")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_empresa")
private Long idEmpresa;

Browser other questions tagged

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