Reputation: 49087
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.
Upvotes: 7
Views: 12470
Reputation: 153800
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
.
Upvotes: 6
Reputation: 45
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="native"
)
@GenericGenerator(
name = "native",
strategy = "native"
)
use this generator="native" as the database does not support sequences
Upvotes: 1
Reputation: 252
You could use @GeneratedValue(strategy=GenerationType.IDENTITY) in your entity bean. It worked for me on sql database. However the entity would not get that ID after you call em.persist(your entity). So you would need to call em.refresh on that entity.
Upvotes: 0
Reputation:
AUTO means leave it up to the JPA implementation (see the JPA spec). IDENTITY means use autoincrement capabilitity if the RDBMS supports it (mySQL does). Be specific (use IDENTITY) and it would work. This has added benefits if you ever moved to a different JPA implementation that had different logic for "AUTO"
Upvotes: 1