Search code examples
javaspringdatabasehibernatespring-data

Problems with @GeneratedValue in the H2 database


Hello StackOverflow Community, I have a problem with the annotation @GenerateValue. I want that JPA generates the values for my ID column. But I have another column where people can write some sort of tasks (todo list).

My code seems like this:

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String name;

and I have a SQL data file that write some data at the beginning in my h2 database:

    INSERT INTO task VALUES(1, 'go to the gym');
    INSERT INTO task VALUES(2, 'eat with tom');
    INSERT INTO task VALUES(3, 'meetup');
    INSERT INTO task VALUES(4, 'doing some homeworks');
    INSERT INTO task VALUES(5, 'doing some exercise');
    INSERT INTO task VALUES(6, 'studying with Mat');

my problem is, when I delete the integer values on my SQL data file, my compiler says always that I have to declare an id for the tasks, but I thought the @GenerateValue automatically generate the id's for me?


Solution

  • Note: Use @GeneratedValue on Primary Key Cols

    You have to use @GeneratedValue(strategy = GenerationType.IDENTITY) or @GeneratedValue(strategy = GenerationType.SEQUENCE) When your strategy is IDENTITY you don't need to define a sequence in your database. But when your strategy is SEQUENCE make sure that you have sequence on database level.

    Also, when using auto-generated ids, don't specify them explicitly when inserting.

    Correct insert query when you have primary key column in table:

    INSERT INTO task(description) VALUES('go to the gym');
    

    but I thought the "@GenerateValue" automatically generate the id's for me?

    It's a not the correct assumption, Hibernate just uses ids provided by db. To get it to work you need to create index/sequence for your primary key column.

    Refer: https://stackoverflow.com/a/53446726/792580 to know more about Generation Strategies