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

I have an object that should automatically get the identifier from the database. I use MySQL, so I expect the annotation @GeneratedValue(strategy=GenerationType.AUTO) be resolved by IDENTITY backstage and NOT SEQUENCE . However, when I try to save a new object, it does not say that hibernate_sequence not found. Obviously, instead of identity, a sequence strategy is used.

I installed the dialect in persistence.xml: org.hibernate.dialect.MySQL5InnoDBDialect

Hibernate version 4.2.0.CR1

All the sources that I read say that it should use the identifier when connecting to MySQL with auto as a strategy.

+6
source share
4 answers

If you use extended identifiers:

  properties.put("hibernate.id.new_generator_mappings", "true"); 

then SequenceStyleGenerator is used , and since MySQL does not support sequences, it will return to the TABLE generator . Therefore, it searches for "hibernate_sequence", which is the name of the default sequence table.

If you are not using new generators, then the "native" generation is used, which will look for:

 public Class getNativeIdentifierGeneratorClass() { if ( supportsIdentityColumns() ) { return IdentityGenerator.class; } else if ( supportsSequences() ) { return SequenceGenerator.class; } else { return TableHiLoGenerator.class; } } 

Therefore, he chooses from:

  • identity
  • sequence
  • hilo

depending on your current database capabilities.

In this case, for MySQL, it will always select the identifier. See this article for more information.

+6
source

AUTO means rejection of the JPA implementation (see the JPA specification). IDENTITY means using the auto-increment feature if RDBMS supports it (mySQL does). Be specific (use IDENTITY) and it will work. This added benefits if you ever switched to a different JPA implementation that had different logic for "AUTO"

+1
source

You can use @GeneratedValue (strategy = GenerationType.IDENTITY) in your bean entity. It worked for me in the sql database. However, the object will not receive this identifier after calling em.persist (your object). Therefore, you will need to call em.refresh on this object.

0
source
 @Id @GeneratedValue( strategy= GenerationType.AUTO, generator="native" ) @GenericGenerator( name = "native", strategy = "native" ) 

use this generator = "native" as the database does not support sequences

0
source

Source: https://habr.com/ru/post/974837/


All Articles