An entity which has ID but the data in corresponding table was added manually, for this reason @GeneratedValue annotation was never added. Now I need to create records in this table through code and want my ID to be auto-incremented.
On adding @Id @GeneratedValue(strategy = GenerationType.AUTO) Integer id;
The exception I get is:
java.sql.SQLException: Field 'id' doesn't have a default value
Is there a way to make this work?
CodePudding user response:
You need to change the column definition in the database to add a default value of "AUTO_INCREMENT".
For Mysql:
ALTER TABLE yourtable MODIFY COLUMN ID INT NOT NULL AUTO_INCREMENT;
I think you should also set the next AUTO_INCREMENT value for the table to the actual maximum value of the id 1:
ALTER TABLE yourtable AUTO_INCREMENT = new_value;