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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With