JPA @GeneratedValue(strategy=GenerationType.AUTO) does not work on MySQL
Solution 1
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:
- identity
- sequence
- hilo
depending on your current database capabilities.
In this case for MySQL, it will always pick IDENTITY
.
Solution 2
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="native"
)
@GenericGenerator(
name = "native",
strategy = "native"
)
use this generator="native" as the database does not support sequences
LuckyLuke
Updated on June 09, 2022Comments
-
LuckyLuke almost 2 years
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 toIDENTITY
behind the scenes and NOTSEQUENCE
. However, when I try to persist a new entity it fails saying thathibernate_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.