MySQL
CREATE TABLE `role` (
`id_role` INT(11) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id_role`)
) AUTO_INCREMENT=1;
冬眠
@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;
}
}
鉴于上述背景,当创建一个新的角色
时,谁负责id_role
列的自动递增?换句话说,Hibernate是在运行create
SQL语句之前设置主键值,还是将其设置为null
并让MySQL在取回所选主键的同时自动递增该字段?
要使用MySQLAUTO_INCREMENT
列,您应该使用IDENTITY
策略:
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
这是您在MySQL中使用AUTO
时会得到的:
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
这实际上相当于
@Id @GeneratedValue
private Long id;
如果您指定GenerationType. IDENTITY
,则数据库将负责分配初始标识符。所以,使用
@GeneratedValue(strategy=GenerationType.IDENTITY)
会让DB负责。
这绝对是数据库。每个db方言对Hibernate来说都有一个稍微不同的方式来查询新分配的ID是什么,这样它就可以在你的实体上设置它