Hibernate @GeneratedValue null error for primary key

后端 未结 3 485
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 03:53

I am using Hibernate to save an object in the database. I am generating my primary key with @GeneratedValue annotation.

Here is my code Vendor class

         


        
相关标签:
3条回答
  • 2020-12-19 04:20

    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
    @GeneratedValue
    private 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.

    0 讨论(0)
  • 2020-12-19 04:24

    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.

    0 讨论(0)
  • 2020-12-19 04:33

    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) )

    0 讨论(0)
提交回复
热议问题