Hibernate @GeneratedValue null error for primary key Hibernate @GeneratedValue null error for primary key sql-server sql-server

Hibernate @GeneratedValue null error for primary key


If you use the strategy javax.persistence.GenerationType.IDENTITY for @GeneratedValue your table must have an identity generator. This can be done including an AUTO_INCREMENT to your primary key.

Example:CREATE TABLE Vendor(ID int NOT NULL AUTO_INCREMENT,PRIMARY KEY (ID))


Your vendor_ID has no default value but it has NOT NULL constraint. When you're doing INSERT, you have to set vendor_ID, or if you don't want to set it manually then you should set AUTO_INCREMENT attribute to generate a unique identity for new rows. Remember, if you don't set any value for your id field, it is supposed to be null or default value (or it will do an auto increment if you set that attribute).

The @GeneratedValue annotation just tells Hibernate that the database is generating this value itself. So the AUTO_INCREMENT should be defined in the database as well.


I don't know if the Hibernate ORM has been updated that much but currently you have to omit the decorator @Column() if you use @GeneratedValue.

So your code will be

@Id@GeneratedValueprivate int vendor_ID;

instead of

@Id@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)@Column(name="vendor_ID", unique = true, nullable = false)private int vendor_ID;

Hope it helps.