问题
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