Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot add or update a child row: a foreign key constraint fails - Bidirectional mapping in hibernate

Hi I have a problem with JPA...

DB:

Database

Java classes (irrelevant fields are ommited):

User:

@Entity
public class User{
    @Id
    private int iduser;

    //bi-directional many-to-one association to UserInfo
    @OneToMany(mappedBy="user", cascade= {CascadeType.ALL}, fetch=FetchType.EAGER)
    private List<UserInfo> userInfos;
}

UserInfo:

@Entity
@Table(name="user_info")
public class UserInfo {
    @Id
    @Column(name="iduser_info")
    private int iduserInfo;

    //bi-directional many-to-one association to User
    @ManyToOne  
    private User user;
}

Currently when I try to do this (again I omitted setting irrelevant fields):

User u = new User();            
UserInfo info = new UserInfo();
u.addUserInfo(info);

em.persist(u); // save user

I get this error:

Cannot add or update a child row: a foreign key constraint fails (`webstore`.`user_info`, CONSTRAINT `fk_user_info_user` FOREIGN KEY (`user_iduser`) REFERENCES `user` (`iduser`) ON DELETE NO ACTION ON UPDATE NO ACTION)

I have been banging my head all day and I can't figure it out... I have also searched for solutions here but they all suggest that this error shows that I want to enter UserInfo without user_iduser value entered, but even if I add this before persist:

info.setUser(u);

it still doesn't work - is bidirectional mapping even supported with cascading? The desired effect is that User should be inserted and then all the UserInfos in the list after it refering the original User. How can I achieve that?

I don't want to do

SET foreign_key_checks = 0/1;

everytime =(

like image 361
BizzyDizzy Avatar asked Mar 16 '23 12:03

BizzyDizzy


2 Answers

Try:

@ManyToOne
@JoinColumn(name="user_iduser", nullable=false)
private User user;

Then see if this works. I'm assuming that in user_info table, the user_id field is NOT NULL in your RDBMS. Also, since it's bidirectional, you will have to setXXX on UserInfo and User.

User u = new User();            
UserInfo info = new UserInfo();
info.setUser(u);
u.addUserInfo(info);

em.persist(u); // save user

Update: Are you sure you're specifying an ID for both User and UserInfo? It looks like the ID is not set hence there is no reference to link UserInfo to User.

If the ID are AUTO_INCREMENT, then add the following after @Id annotation:

@GeneratedValue(strategy=GenerationType.IDENTITY)
like image 81
Buhake Sindi Avatar answered Apr 15 '23 03:04

Buhake Sindi


I also had this error, fixed this error by adding @GeneratedValue(strategy = GenerationType.IDENTITY) annotation on top of iduser and you must have foreign keys CASCADE ON DELETE, UPDATE.

like image 26
Xan Avatar answered Apr 15 '23 01:04

Xan