简体   繁体   中英

java.sql.SQLException: 'Field 'voc_id' doesn't have a default value'. using Spring JPA

I'm trying to insert Voc, Recovery class in One to one relationship.
Voc is gonna be inserted first and it's pk will get into Recovery class as it's foreign key. (Which is gonna be used like PK of Recovery class)


This is Voc class, which is parent.
 @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name="voc") public class Voc { @Id @Column(name="id") @GeneratedValue(strategy=GenerationType.IDENTITY) int id; @OneToOne(mappedBy="voc", cascade=CascadeType.ALL) Recovery recovery; // some other variables... }

And this is Recovery class, which is child.
 @Data @Entity @Table(name="recovery") public class Recovery { @Id @Column(name="voc_id") @GeneratedValue(strategy=GenerationType.IDENTITY) int vocId; @OneToOne @PrimaryKeyJoinColumn(name="voc_id") Voc voc; // some other variables... }

I'm trying to do the way of No.3 from this .
But when I call the save() method of JpaRepository, it throws error message ' Field 'voc_id' doesn't have a default value '.
What am I missing?
Or is there better way than this to make what I want?

Error states that 'voc_id' doesn't have a default value that is while creating table there is no default value assigned by you in case voc_id is NOT NULL. So, if in code there is null value getting assigned to voc_id it will throw exception. Best way to avoid this error is to define some default value to all NOT NULL attributes in create table query. In your case you also need to check why it is getting null value since it is auto generated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM