Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who is responsible of the auto-incrementation of a 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;

Hibernate

@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 of the auto-incrementation of 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 does it set it to null and let MySQL auto-increments the field while getting back the chosen primary key?

like image 955
sp00m Avatar asked Mar 13 '13 16:03

sp00m


2 Answers

To use a MySQL AUTO_INCREMENT column, you are supposed to use an IDENTITY strategy:

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

Which is what you'd get when using AUTO with MySQL:

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

Which is actually equivalent to

@Id @GeneratedValue
private Long id;
like image 146
Sujay Mumbaraddi Avatar answered Oct 19 '22 17:10

Sujay Mumbaraddi


If you specify GenerationType.IDENTITY , then the database will be in charge assigning the initial identifier. So, using

@GeneratedValue(strategy=GenerationType.IDENTITY)

would leave the DB in-charge.

like image 3
JustDanyul Avatar answered Oct 19 '22 17:10

JustDanyul