Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate id generator AUTO_INCREMENT at h2 and MySQL in a cluster

For testing I'm using the H2 database.

For production it's MySQL.

I understrand that both support AUTO_INCREMENT (mysql / h2), but it seems like Hibernate doesn't work this way.

identity is supported for MySQL. Fine.
What about H2? Should I write my own generator or...? (using the org.hibernate.id.IdentifierGenerator interface as the doc says).

I must have a nice clean & quick way to get an ID (of type long by the way) from the database itself because the application is in a cluster (i.e several servers INSERT into the database at once)... that's why increment is definitely not for me.

Thanks!

like image 509
Poni Avatar asked Oct 31 '25 17:10

Poni


1 Answers

You should just annotate your id property which needs the generated value with @GeneratedValue. This will automatically select the appropriate generation strategy for the database you're using. See GenerationType.AUTO for more details.

Your property will look like this:

@Id
@GeneratedValue
private long id;
like image 124
Alex Barnes Avatar answered Nov 03 '25 09:11

Alex Barnes