问题描述
Father对Child是单向一对多,以下是我写的代码Father类:publicclassFather{privateintfid;privateStringcardId;privateStringname;privateSet<Child>childs=newHashSet<Child>();publicFather(StringcardId,Stringname){super();this.cardId=cardId;this.name=name;}publicintgetFid(){returnfid;}publicvoidsetFid(intfid){this.fid=fid;}publicStringgetCardId(){returncardId;}publicvoidsetCardId(StringcardId){this.cardId=cardId;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicSet<Child>getChilds(){returnchilds;}publicvoidsetChilds(Set<Child>childs){this.childs=childs;}}Father.hbm.xml:<hibernate-mapping><classname="lyu.zlx.domain.Father"table="tbl_father_info"><idname="fid"type="integer"><columnname="fid"not-null="true"/><generatorclass="increment"/></id><propertyname="cardId"type="java.lang.String"column="cardid"/><propertyname="name"type="java.lang.String"column="name"/><setname="childs"inverse="true"cascade="all"><keycolumn="fatherid"/><one-to-manyclass="lyu.zlx.domain.Child"/></set></class></hibernate-mapping>Child类:publicclassChild{privateintcid;privateStringcardId;privateStringname;privateintfatherId;publicintgetFatherId(){returnfatherId;}publicvoidsetFatherId(intfatherId){this.fatherId=fatherId;}publicChild(StringcardId,Stringname){super();this.cardId=cardId;this.name=name;}publicintgetCid(){returncid;}publicvoidsetCid(intcid){this.cid=cid;}publicStringgetCardId(){returncardId;}publicvoidsetCardId(StringcardId){this.cardId=cardId;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}}Child.hbm.xml<hibernate-mapping><classname="lyu.zlx.domain.Child"table="tbl_child_info"><idname="cid"type="integer"><columnname="cid"not-null="true"/><generatorclass="increment"/></id><propertyname="cardId"type="java.lang.String"column="cardid"/><propertyname="name"type="java.lang.String"column="name"/><propertyname="fatherId"type="java.lang.Integer"column="fatherid"/></class></hibernate-mapping>出现以下错误:Causedby:java.sql.BatchUpdateException:Cannotaddorupdateachildrow:aforeignkeyconstraintfails(`db`.`tbl_child_info`,CONSTRAINT`FK7738ED128EB76D0F`FOREIGNKEY(`fatherid`)REFERENCES`tbl_father_info`(`fid`))一下午了,在网上找了许多答案,还是没有找到准确的解释。有请各位大侠。谢谢!
解决方案
解决方案二:
楼主,单向一对多中外键已经由一的一端维护了,在多的那端就不需要再配fatherid属性了去掉映射文件中的<propertyname="fatherId"type="java.lang.Integer"column="fatherid"/>这行就OK了!