Who is responsible for automatically increasing the primary key between MySQL and Hibernate?

MySQL

CREATE TABLE `role` ( `id_role` INT(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id_role`) ) AUTO_INCREMENT=1; 

Sleep mode

 @Entity public class Role { private Integer idRole; @Column(name = "id_role", precision = 10) @GeneratedValue @Id public Integer getIdRole() { return idRole; } public void setIdRole(Integer idRole) { this.idRole = idRole; } } 

Given the above background, who is responsible for automatically increasing the id_role column when creating a new role ? In other words, does Hibernate set the primary key value before running the create SQL statement or set it to null and allows MySQL to automatically increase the field when the selected primary key returns?

+4
source share
3 answers

To use the AUTO_INCREMENT MySQL AUTO_INCREMENT , you must use the IDENTITY strategy:

 @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; 

What do you get when using AUTO with MySQL:

 @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; 

It is actually equivalent

 @Id @GeneratedValue private Long id; 
+6
source

If you specify GenerationType.IDENTITY then the source identifier will be set in the database. So using

 @GeneratedValue(strategy=GenerationType.IDENTITY) 

will free the database.

+3
source

It is definitely a database. Each db dialect has a slightly different way for Hibernate to then request that a new assigned identifier so that it can set it on your entity.

0
source

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


All Articles