I have an entity that is supposed to get an id from the database automatically. I use MySQL so I would expect annotating that @GeneratedValue(strategy=GenerationType.AUTO)
would resolve to IDENTITY
behind the scenes and NOT SEQUENCE
. However, when I try to persist a new entity it fails saying that hibernate_sequence
was not found. It obviously use sequence strategy instead of identity.
I have set the dialect in the persistence.xml to: org.hibernate.dialect.MySQL5InnoDBDialect
Hibernate version 4.2.0.CR1
All sources that I read says that it should use identity when connecting to MySQL with auto as strategy.
If you're working with a MySQL database, you should always use GenerationType. IDENTITY. It uses an autoincremented database column and is the most efficient approach available.
GenerationType. AUTO This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used.
GenerationType.It relies on an auto-incremented database column and lets the database generate a new value with each insert operation. From a database point of view, this is very efficient because the auto-increment columns are highly optimized, and it doesn't require any additional statements.
If you are using the enhanced identifiers:
properties.put("hibernate.id.new_generator_mappings", "true");
then the SequenceStyleGenerator
is used, and since MySQL doesn't support sequences it will fall-back to TABLE
generator. That's why it looks for "hibernate_sequence", which is the default sequence table name.
In case you don't use the new generators, then the native
generation strategy is used, which will look for:
public Class getNativeIdentifierGeneratorClass() {
if ( supportsIdentityColumns() ) {
return IdentityGenerator.class;
}
else if ( supportsSequences() ) {
return SequenceGenerator.class;
}
else {
return TableHiLoGenerator.class;
}
}
So it chooses from:
depending on your current database capabilities.
In this case for MySQL, it will always pick IDENTITY
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With