3

I have been searching through different forums for information and I have tried different solutions, but I'm still unable to correct my issue.

I am using hibernate4 annotations for mapping my entities. Auto increment key is not detected when tables are created using hibernate in mysql.

I have the following code:

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

I have also tried:

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

With hibernate the id is automatically assigned to a row, but in the mysql table it has no AutoIncrement Constraint. I have to mark field as AI manually. This becomes problematic when I manually insert a record for testing or use jdbc statements for the table. Please let me know what I am missing in configuration that is preventing the hibernate id from assigning an AutoIncrement Contraint.

Nyk
  • 83
  • 9
maimoona
  • 617
  • 8
  • 16

1 Answers1

5

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;
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    Do not do that! If any other entity has a reference to your response entity (in the db table, not just a backreference in the model) than the foreign key field will be autoincrement, too! –  Feb 20 '14 at 15:56
  • It doesn't seem good to me.. See http://stackoverflow.com/questions/4102449/how-to-annotate-mysql-autoincrement-field-with-jpa-annotations – Bruno Medeiros Sep 02 '15 at 19:38