Issue
I have a class that is an entity of a table from a PostgreSQL database:
@Entity
@Table(name = "users")
public class User {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Getter private Long id;
...
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL NOT NULL UNIQUE,
...
When the application starts, this table fills with some test data (from .sql file trough "INSERT INTO..."). However, when a new instance is created in the database trough Hibernate, the ID always starts with one, forcing me to create it multiple times until generated ID reaches the required value.
I need the ID counter to start with a number, that is one more than the ID of the previous record in the table. Ideally not requiring me to manually specify the ID value.
Solution
You can define your entity like this:
@Entity
@Table(name = "users")
@SequenceGenerator(name = "sequence", sequenceName = "mySequence")
public class User {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
@Getter private Long id;
And then in your .sql file write insert queries like this:
INSERT INTO users values (select nextval('mySequence'), ...
select nextval('mySequence')
will give you next available value from sequence table
Answered By - Krzysztof K
Answer Checked By - Mary Flores (JavaFixing Volunteer)