问题描述
写了两个类: Subject(一端) Comment(多端)其对应hbm xml(截取)为:subject.hbm.xml: <set name="comments" lazy="true" inverse="true" cascade="all" sort="unsorted" > <cache usage="read-write" /> <key column="subjectid" /> <one-to-many class="com.module.Comment" /> </set>//***************************************comment.hbm.xml: <many-to-one name="subject" class="com.module.Subject" cascade="none" outer-join="auto" update="true" insert="true" column="subjectid" />问题:当删除subject时提示:- SQL Error: 1451, SQLState: 23000- Duplicate key or integrity constraint violation, message from server: "Cannot delete or update a parent row: a foreign key constraint fails (`lnc/t_comment`, CONSTRAINT `FKF437E194F69C747` FOREIGN KEY (`subjectid`) REFERENCES `t_subject` (`id`))"- Could not synchronize database state with sessionorg.springframework.dao.DataIntegrityViolationException: Hibernate operation: could not delete: [com.module.Subject#32769]; SQL []; Duplicate key or integrity constraint violation, message from server: "Cannot delete or update a parent row: a foreign key constraint fails (`lnc/t_comment`, CONSTRAINT `FKF437E194F69C747` FOREIGN KEY (`subjectid`) REFERENCES `t_subject` (`id`))"; nested exception is java.sql.SQLException: Duplicate key or integrity constraint violation, message from server: "Cannot delete or update a parent row: a foreign key constraint fails (`lnc/t_comment`, CONSTRAINT `FKF437E194F69C747` FOREIGN KEY (`subjectid`) REFERENCES `t_subject` (`id`))"java.sql.SQLException: Duplicate key or integrity constraint violation, message from server: "Cannot delete or update a parent row: a foreign key constraint fails (`lnc/t_comment`, CONSTRAINT `FKF437E194F69C747` FOREIGN KEY (`subjectid`) REFERENCES `t_subject` (`id`))"at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1977)at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1163)at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1272)at com.mysql.jdbc.Connection.execSQL(Connection.java:2236)at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1741)at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1588)at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)at net.sf.hibernate.impl.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:22)at net.sf.hibernate.persister.EntityPersister.delete(EntityPersister.java:581)at net.sf.hibernate.impl.ScheduledDeletion.execute(ScheduledDeletion.java:29)at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2449)at net.sf.hibernate.impl.SessionImpl.executeAll(SessionImpl.java:2435)at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2397)at net.sf.hibernate.impl.SessionImpl.flush(SessionImpl.java:2261)请碰到过这个问题的朋友帮我看看(inverse="false" 时可以删除‘一端’,但我想把维护交给‘多端‘Comment)? 问题补充:mrliang 写道
解决方案
在删除subject时,因为你在<set>标签中有inverse="true"让<key>标签失效,这样在一端这方就不能准确获得外键信息,所以直接删除会报错,应该是要先解除关系之后再删除
解决方案二:
把你的删除代码贴上来看看
解决方案三:
你要删除的subject是一端而不是多端啊,当然会外键冲突了。
解决方案四:
维护就是要交给多的 一端