Generate UUID values by default for each row on column of UUID type in H2 Database Engine

让人想犯罪 __ 提交于 2019-11-27 06:21:05

问题


In the H2 database, on a table with a column of UUID data type, how do we specify that we want H2 to generate a UUID value by default when an INSERT omits that field?

I know how to generate a UUID. I have read the Question, How to insert a specific UUID in h2 database?.

My question is about how to ask H2 to generate the UUID value on my behalf.


回答1:


You can use built-in function RANDOM_UUID():

create table test(id int primary key, data uuid default random_uuid());
insert into test(id) values(1);
select * from test;

Note that using the UUID (or any other randomly generated data) as the primary key will result in performance problems if there are more than a few million rows (with relational databases in general, not just with H2).




回答2:


googling for hours I've created a simple solution, according to @Thomas Mueller

with hibernate and jpa:

@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
        name = "UUID",
        strategy = "org.hibernate.id.UUIDGenerator"
)
@Column(name = "ID", updatable = false, nullable = false)
@ColumnDefault("random_uuid()")
@Type(type = "uuid-char")
@Getter
@Setter
private UUID id;

So @Type(type = "uuid-char") makes your field a VARCHAR(255) if you need it (it's binary by default)

And @ColumnDefault("random_uuid()") puts the dedault value for generated table DDL

Hope this helps



来源:https://stackoverflow.com/questions/41112332/generate-uuid-values-by-default-for-each-row-on-column-of-uuid-type-in-h2-databa

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