Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 809
Yuto Avatar asked Mar 20 '20 06:03

Yuto


2 Answers

You have to use @GeneratedValue(strategy = GenerationType.IDENTITY) or @GeneratedValue(strategy = GenerationType.SEQUENCE) and make sure that you have index or sequence on database level. Also when using auto-generated ids, don't specify them explicitly when inserting.

Correct:

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.

like image 100
slesh Avatar answered Oct 20 '22 15:10

slesh


You're mixing up sql and hibernate. @GeneratedValue is declared in your java code, so that hibernate knows, that when you're persisting an entity without an id, it should be generated by given strategy.

On the other hand you tried to make insertions using sql without passing primary key, so you're explicitly said, that it should be NULL, which is clearly against the constraint.

like image 2
Andronicus Avatar answered Oct 20 '22 14:10

Andronicus