Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GeneratedValue in Postgres

I have my entity class mapped like below:

@Entity
@Audited
@Table(name="messages_locale")
public class Locale {

    @Id
    @GeneratedValue
    @Getter @Setter //Project Lombok's annotations, equal to generated getter and setter method
    private int id;
        (...)

I create clean new database ,and properties:

< prop key="hibernate.hbm2ddl.auto" >create < /prop>

WHY THE HELL (Sorry, almost two days wasted on this bug) after created database, i got a sequence in my postgres db?:

CREATE SEQUENCE hibernate_sequence
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 2
  CACHE 1;
ALTER TABLE hibernate_sequence
  OWNER TO postgres;

I dont want to have a sequence, I want to have just auto increment auto generated values..

like image 884
Cichy Avatar asked Oct 28 '12 08:10

Cichy


People also ask

What is the use of @GeneratedValue?

Annotation Type GeneratedValueProvides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.

Does Postgres support GenerationType identity?

In the case of Postgres, it happens that defining a SERIAL column is implemented by creating a sequence and using it as a default column value. But it is the database that is populating the id field so using GenerationType. IDENTITY tells Hibernate that the database is handling id generation.

Can we use Hibernate with PostgreSQL?

Out of the box, Hibernate works pretty well with PostgreSQL databases.

What is serial datatype in Postgres?

PostgreSQL has a special kind of database object generator called SERIAL. It is used to generate a sequence of integers which are often used as the Primary key of a table. Syntax: variable_name SERIAL.


Video Answer


1 Answers

In PostgreSQL auto-increment is handled using the SERIAL pseudo type. You use this type when you execute CREATE TABLE.

Now to the point - this SERIAL pseudo type creates a sequence. Autoincrement in PostgreSQL is handled using the created sequence. The default value of the id column becomes - nextval('your_sequence_name').

In Hibernate for an User entity:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_seq_gen")
@SequenceGenerator(name = "users_seq_gen", sequenceName = "users_id_seq")
public Long getId() {
     return id;
}

Read here:

http://www.postgresql.org/docs/8.4/static/datatype-numeric.html#DATATYPE-SERIAL

http://www.neilconway.org/docs/sequences/

like image 129
Petar Minchev Avatar answered Oct 03 '22 22:10

Petar Minchev