how to set H2 primary key id to auto_increment? how to set H2 primary key id to auto_increment? sql sql

how to set H2 primary key id to auto_increment?

You should use the JPA annotations @Id and @GeneratedValue for your ID.

Your SQL looks valid. Can you post the error message?

I had the same problem. I am not sure if the root-cause is the same. But there turned to be a perfectly logical explanation. So here is what I discovered.

First of all, there are at least 2 distinct ways to create auto-incremented keys.

1st way: (xml)

If you work with an xml-based configuration that holds your class info.Then you can put something as follows in your classname.hbm.xml file.

<id name="id">    <generator class="sequence"><param name="sequence">my_id_seq</param</generator></id>

To import this file you will have something like the following in your hibernate.cfg.xml file: (or possibly with a resource attribute)

<!--  Mapping files  --><mapping file="classname.hbm.xml"/>

But the important thing here is that it is now actually JAVA that will increment the keys. If you would have checked the sql that was used to generate the table, you would have noticed that it did not hold an auto-incremented field definition for the id column.

2nd way: (annotations)

A totally different way of doing things is to put everything in annotations, like you showed in your question.


in your hibernate.cfg.xml file you will have something like:

<!--  Mapping files  --><mapping class="package.subpackage.MyClassName"/>

The GenerationType.IDENTITY is indeed the default value, so you do not have to supply it per se. But anyway this time the table will be generated differently. Namely as follows:


Aha! That's interesting. This time the sequence generation will not be performed by JAVA it will be performed by the database itself.

What went wrong:

We are all experimenting and trying things out of course. If you first decided to do it with the xml-files and afterwards you decided to do it with annotations after all. Then of course that means you will have to regenerate your tables as well. If you forget to do so, then you will get errors like doniyor did.

How to fix it:

just add the following line to your hibernate.cfg.xml and reboot your application.

<!-- Drop and re-create the database schema on startup --><property name="">create</property>

The table has been destroyed and regenerated.