2011-04-08 89 views
0

这个错误让我当我尝试使用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; 
    } 
} 

我第一次插入对象“用户”在数据库中,然后我尝试插入这个用户在这个表'account_confirmation',但是不可能..我真的不明白为什么会发生这种情况。

有什么想法?

编辑: // 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) 

最好的问候, 瓦尔特·恩里克。

+0

难道你不应该不得不告诉hibernate用户是外键吗?也许在这种情况下是一对一的关系?我不积极如何使用注释做到这一点。抱歉。 – hooknc 2011-04-08 20:55:15

+0

@hooknc,它不工作,我尝试你的建议,但不断返回: 无法添加或更新子行:外键约束失败('bytecodete'.'account_confirmation',CONSTRAINT'FK_account_confirmation_1' FOREIGN KEY('email ')参考'user'('email')ON DELETE CASCADE ON UPDATE CASCADE) – 2011-04-08 21:09:19

+1

您应该可以打开hibernate日志记录来查看SQL执行的确切内容。对于log4j,您可以在DEBUG上使用“org.hibernate.SQL”。您也可以考虑在DEBUG上使用“org.hibernate”。如果你的用户对象的映射有问题,你有该用户对象的映射,并且你能够添加一个用户到你的数据库? – hooknc 2011-04-08 21:33:31

回答

0

您是否将用户和帐户确认保存在同一会话中?这是一种双向关系还是只是单向的? (也许你还应该发布类用户的内容)

相关问题