问题
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?
回答1:
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;
回答2:
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.
回答3:
It is definitely the database. Each db dialect has a slightly different way for Hibernate to then query what that newly assigned ID was so it can set it on your entity
来源:https://stackoverflow.com/questions/15390856/who-is-responsible-of-the-auto-incrementation-of-a-primary-key-between-mysql-and