---
title: "一对多 Cannot add or update a child row"
author: "east_java"
date: "2009-12-09T23:10:05Z"
tags: []
categories: ["编程语言"]
slug: "cannot-add-or-update-a-child-row"
draft: false
lastmod: "2009-12-09T23:12:45Z"
id: 545132
url: "https://japi.iteye.com/blog/545132"
---

其实这个问题是在更新数据的时候出现的。

 

在使用getOne()并进行更新的时候就出现了这个问题。。

 

开始是以为是FetchType.LAZY的原因，但改成EAGER后还是没有解决。。

 

发现 现在对hibernate的了解远远不如以前，也可能以前没有理解透吧。

 

现在这个问题其实又是注解的配置问题。

 

@Column(name = "chapter", unique = false, nullable = true, insertable = true, updatable = true, length = 11)  
    public java.lang.Integer getChapter() {  
        return this.chapter;  
    }

 

@ManyToOne(fetch = FetchType.EAGER)  
    @JoinColumn(name = "chapter", nullable = true, insertable = false, updatable = false)  
    public WikiChapter getWikiChapter() {  
        return wikiChapter;  
    }

 

使用了两个chapter映射。

 

之前都是以chapter来操作的，如果要对WikiChapter来操作，就是个空值。所以在保存一个文章的时候除了 对chapter进行赋值，还得再去wikichaper进行赋一次，不然取不到wikichapter使用。

 

这还只是有小问题，但在对wikichapter进行更新的时候就出这个问题。。（如果数据库中不设置外键是没有这个问题的，但修改后，内存中没有关联的wikichapter值，就算是对wikichapter设置了新值）

其实是name = "chapter", nullable = true, insertable = false, updatable = false这个的问题，不能进行update,insert。

 

这两处不能都设置为true。。

 

所以还是以对象为准，操作对象，而不是字段。

 

 

Caused by: java.sql.BatchUpdateException: Cannot add or update a child row: a foreign key constraint