简体   繁体   中英

Hibernate:Cannot add or update a child row: a foreign key constraint fails

this error gives me when i try to insert (save) an user using hibernate:

//SQL
DROP TABLE IF EXISTS `bytecodete`.`account_confirmation`;
CREATE TABLE  `bytecodete`.`account_confirmation` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  KEY `FK_account_confirmation_1` (`email`),
  CONSTRAINT `FK_account_confirmation_1` FOREIGN KEY (`email`) REFERENCES `user` (`email`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;



// HIBERNATE
@Entity
@Table(name = "account_confirmation", catalog = "bytecodete")
public class AccountConfirmation implements java.io.Serializable {

    private Integer id;
    private User user;

    public AccountConfirmation() {
    }

    public AccountConfirmation(User user) {
        this.user = user;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "email", nullable = false)
    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

I first insert the object 'user' in the database then i try to insert this user in this table 'account_confirmation', but isn't possible.. i really don't understand why this happens.

Any idea ?

EDIT: // LOG4J

Hibernate: 
    insert 
    into
        bytecodete.user
        (email, password, type) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        bytecodete.person
        (birthDate, cpf, gender, idFacebook, name, tokenFacebook, idUser) 
    values
        (?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        bytecodete.account_confirmation
        (email) 
    values
        (?)
18:45:40,745  WARN JDBCExceptionReporter:77 - SQL Error: 1452, SQLState: 23000
18:45:40,746 ERROR JDBCExceptionReporter:78 - Cannot add or update a child row: a foreign key constraint fails (`bytecodete`.`account_confirmation`, CONSTRAINT `FK_account_confirmation_1` FOREIGN KEY (`email`) REFERENCES `user` (`email`) ON DELETE CASCADE ON UPDATE CASCADE)

Best regards, Valter Henrique.

Are you saving the user and account confirmation in the same session? Is this a bidirectional relation or just unidirectional? (Maybe you should also post the content of the class user)

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