Manually update the counter used for generation of primary key in Hibernate?

前端 未结 2 428
悲&欢浪女
悲&欢浪女 2021-01-24 16:41

In my spring project, the tables in database are created automatically by Hibernate using my entity classes as base, but I insert some default values in the table manually (usin

相关标签:
2条回答
  • 2021-01-24 17:36

    Call this SQL query once per table to set the sequence to the next free number:

    SELECT setval('tblname_id_seq', max(id)) FROM tblname;
    

    tblname being the actual name of the table.

    Hibernate may use a different naming convention, or the sequence may have been renamed. If you can't find the sequence behind the serial column, check with (per documentation):

    SELECT pg_get_serial_sequence(tblname, column_name)
    

    More details:
    Modify Django AutoField start value
    How to import a CSV to postgresql that already has ID's assigned?

    0 讨论(0)
  • 2021-01-24 17:40

    The problem here might be that you declare the id as a primitive instead of a wrapper.

    So instead of:

    private int id;
    

    You should have:

    private Integer id;
    

    When you create the entity with the id is initialized as 0, instead of NULL.

    That's why you get duplicate id constraint violation exceptions.

    Only when the id is NULL the AUTO generation strategy will delegate the id assignment to the database.

    0 讨论(0)
提交回复
热议问题