hibernate not generate auto increment constraint on mysql table

守給你的承諾、 提交于 2019-12-07 17:58:44

问题


I have been searching through different forums for the problem and had tried different solutions but i am still unable to find any correct answer for my problem.

I am using hibernate4 annotations for mapping my entities. everything works fine but only auto increment key is not detected when tables are created using hibernate in mysql.

i have following code:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private int responseId;

i also have tried

@Id
@GenericGenerator(name="generator", strategy="increment")
@GeneratedValue(generator="generator")
private int responseId;

With hibernate it works absolutely fine, id is automatically assigned to row, but in mysql table it have no AutoIncrement Constraint. I have to mark field as AI manually. This becomes problematic when i manually insert record for testing or use jdbc statements for the table. Plz let me know what i am missing in configuration that is preventing hibernate to impose AutoIncrement Contraint on respective column.


回答1:


Use the IDENTITY generator, and use the columnDefinition attribute of @Column to specify the type of the column:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "MEDIUMINT NOT NULL AUTO_INCREMENT")
private int responseId;


来源:https://stackoverflow.com/questions/9733619/hibernate-not-generate-auto-increment-constraint-on-mysql-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!