auto increment ID in H2 database

瘦欲@ 提交于 2019-11-28 19:30:54

问题


Is there a way to have an auto_incrementing BIGINT ID for a table. It can be defined like so

id bigint auto_increment

but that has no effect (it does not increment automatically). I would like to insert all fields but the ID field - the ID field should be provided by the DBMS. Or do I need to call something to increment the ID counter?


回答1:


It works for me. JDBC URL: jdbc:h2:~/temp/test2

drop table test;
create table test(id bigint auto_increment, name varchar(255));
insert into test(name) values('hello');
insert into test(name) values('world');
select * from test; 

result:

ID  NAME  
1   hello
2   world



回答2:


IDENTITY

The modern approach uses the IDENTITY type, for automatically generating an incrementing 64-bit long integer.

This single-word syntax used in H2 is an abbreviated variation of GENERATED … AS IDENTITY defined in the SQL:2003 standard. See summary in PDF document SQL:2003 Has Been Published. Other databases are implementing this, such as Postgres.

CREATE TABLE event_ ( 
    pkey_ IDENTITY NOT NULL PRIMARY KEY ,  -- ⬅ `identity` = auto-incrementing long integer.
    name_ VARCHAR NOT NULL ,
    start_ TIMESTAMP NOT NULL , 
    stop_ TIMESTAMP NOT NULL 
) ;



回答3:


Very simple:

id int auto_increment primary key

H2 will create Sequence object automatically




回答4:


You can also use default:

create table if not exists my(id int auto_increment primary key,s text);
insert into my values(default,'foo');



回答5:


id bigint(size) zerofill not null auto_increment,


来源:https://stackoverflow.com/questions/9353167/auto-increment-id-in-h2-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!