hibernate id generator AUTO_INCREMENT at h2 and MySQL in a cluster
Solution 1
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;
Solution 2
Use the native generator, for example
<id name="id" type="int">
<column name="id_column" />
<generator class="native" >
<param name="sequence">id_column_sequence</param>
</generator>
</id>
The generator with the class native
uses the best generation strategy for the database. In the case of MySql this is auto_increment, in the case of Oracle this is a sequence (and for H2 it also should be a sequence, but I've never tried, because I don't use H2). The generator parameter sequence
only is used if it is useful, i. e. for MySql databases the parameter is ignored, and for Oracle it is used.
In that way you can use the same mapping file for different database types (at least as long as the table and column names are the same).
Related videos on Youtube
Poni
Updated on September 15, 2022Comments
-
Poni over 1 year
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 theorg.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 serversINSERT
into the database at once)... that's whyincrement
is definitely not for me.Thanks!
-
Poni almost 12 yearshi and thanks. Sorry but: 1) I'm using XML mapping. 2) I specifically aim to MySQL and H2's feature of auto id generation, and not the alternatives that Hibernate offers such as HiLow etc'.
-
Alex Barnes almost 12 yearsOK so use the XML alternative to the @Generated value. And the default generation strategy will use the database auto id generation.
-
Poni almost 12 yearsWish it was that simple - what is the alternative to
GenerationType.AUTO
? Can you see it ( docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/… )? I don't.