JPA and PostgreSQL with GenerationType.IDENTITY

后端 未结 3 1581
迷失自我
迷失自我 2020-12-05 16:43

I have a question about Postgres and GenerationType.Identity vs Sequence

In this example...

@Id
@SequenceGenerator(name=\"mytable_id_seq\",
                  


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 16:59

    If you have a column of type SERIAL, it will be sufficient to annotate your id field with:

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    

    This is telling Hibernate that the database will be looking after the generation of the id column. How the database implements the auto-generation is vendor specific and can be considered "transparent" to Hibernate. Hibernate just needs to know that after the row is inserted, there will be an id value for that row that it can retrieve somehow.

    If using GenerationType.SEQUENCE, you are telling Hibernate that the database is not automatically populating the id column. Instead, it is Hibernate's responsibility to get the next sequence value from the specified sequence and use that as the id value when inserting the row. So Hibernate is generating and inserting the id.

    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.

    These references may help:

    http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators

    https://www.postgresql.org/docs/8.1/static/datatype.html#DATATYPE-SERIAL

提交回复
热议问题