Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA @GeneratedValue(strategy=GenerationType.AUTO) does not work on MySQL

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.

like image 616
LuckyLuke Avatar asked Sep 04 '14 15:09

LuckyLuke


People also ask

What is the recommended GenerationType for MySQL?

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.

What is @GeneratedValue strategy GenerationType Auto?

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.

How does GenerationType auto work?

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.


1 Answers

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.

like image 67
Vlad Mihalcea Avatar answered Oct 06 '22 14:10

Vlad Mihalcea