DEV Community

vaishnavi d
vaishnavi d

Posted on

Error : attempted to assign id from null one-to-one property Contact.user

I have USER(id) and CONTACT(user_id, first, last) table. CONTACT.user_id is the foreign key to USER table.

In User.java:

@id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;

@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Contact contact;

in Contact.java

@id
@Column(name="USER_ID")
private Integer userId;

@MapsId
@OneToOne(mappedBy = "contact")
@JoinColumn(name = "USER_ID")
private User user;
I use userRepository.saveAndFlush(user) to save USER object. Since I am using USER.ID as the foreign key in CONTACT, I need to insert USER before CONTACT, but JPA is Inserting CONTACT first, it sees CONTACT as a member of USER. So I am getting a USER_ID can not be NULL error when inserting CONTACT. What should I do to fix this the order of insert?

Top comments (0)