Manually update the counter used to generate the primary key in Hibernate?

In my spring project, tables in the database are automatically created by Hibernate using my entity classes as the database, but I manually insert some default values ​​into the table (using pgAdmin3).

In this regard, before this, I ran into this problem: when I try to insert a value through Java code into one of the tables that already have values, an error message appears saying that the primary key already exists in the database.

Does anyone know how to solve this problem?

UPDATE

How I declare my primary key in my class:

@Id @Column(name = "id") @GeneratedValue(strategy=GenerationType.AUTO) private int id; 
+1
source share
2 answers

Call this SQL query once in the table to establish the sequence of the following toll free number:

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

tblname is the actual name of the table.

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

 SELECT pg_get_serial_sequence(tblname, column_name) 

More details:
Change Django AutoField Initial Value
How to import CSV into postgresql that already has an ID?

+3
source

The problem here may be that you are declaring id as a primitive instead of a shell.

So, instead of:

 private int id; 

You must have:

 private Integer id; 

When creating an object with an identifier, it initializes to 0, instead of NULL.

This is why you get an id duplication violation exception exception.

Only when the identifier is NULL does the AUTO generation strategy delegate the assignment of the identifier to the database.

0
source

Source: https://habr.com/ru/post/985906/


All Articles