本文介绍了谁负责MySQL和Hibernate之间主键的自动递增?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 $ b`id_role` INT(11)unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY(`id_role`))AUTO_INCREMENT = 1; Hibernate @Entity public class Role { private Integer idRole; $ b @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自动增加字段,同时获得所选主键? 使用MySQL AUTO_INCREMENT 列,您应该使用 IDENTITY 策略: @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; 使用 AUTO 使用MySQL: @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; 其实相当于 @Id @GeneratedValue 私人长ID; MySQLCREATE TABLE `role` ( `id_role` INT(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id_role`)) AUTO_INCREMENT=1;Hibernate@Entitypublic 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 @GeneratedValueprivate Long id; 这篇关于谁负责MySQL和Hibernate之间主键的自动递增?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-12 08:36