当我尝试将java.sql.SQLException
值插入到具有外键约束的列到另一个表时,我得到NULL
:ORA-02291。根据定义,子列在子表中是NULLABLE,它在父表中引用的列是该表的PK。
我很困惑,为什么我得到这个例外。任何有关这方面的帮助将不胜感激。
这是例外和DDL
异常
org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; violated - parent key not found
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:249)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
DDL
ALTER TABLE childtablename ADD CONSTRAINT constraintname FOREIGN KEY ( childtablecolumn )
REFERENCES parenttable(parenttablecolumn) ON DELETE CASCADE;
来自我的JUnit的代码:
result = getJdbcTemplate().update(sql, new Object[]{
notification.value1(),
notification.value2(),
notification.value3(), //this is for the column in contention, it is a int value and i have not initialized this variable
notification.value4(),
notification.value5(),
notification.value6(),
notification.value7(),
notification.value8(),
notification.value9()
});
事实是我可以直接使用查询从SQL开发人员插入带有NULL值的记录。当我以编程方式执行此操作时,它才会失败。
春天可能是罪魁祸首吗?
答案 0 :(得分:1)
感谢所有回复。
Mick的建议工作,即在预准备语句中显式地将值设置为null,并且因为我使用的是spring jdbc模板,所以在我的情况下只需将null值传递给函数中的必需参数,如图所示上面的代码片段
再次粘贴修补程序
如果您使用预备声明,请尝试以下操作:
PreparedStatement ps = myConnection.prepareStatement(
"INSERT INTO childtablename (pk_id, childtablecolumn) VALUES (?, ?)");
ps.setInt(1, id);
ps.setNull(2, java.sql.Types.NUMERIC);
在我的案例中有效的解决方案(请参阅以下追踪来自Mick的答案):
result = getJdbcTemplate().update(sql, new Object[]{
notification.value1(),
notification.value2(),
null, //this is for the column in contention, it is a primitive int value and i have not initialized this variable, so i had to do this to make it work
notification.value4(),
notification.value5(),
notification.value6(),
notification.value7(),
notification.value8(),
notification.value9()
});
答案 1 :(得分:-1)
错误消息java.sql.SQLException: ORA-02291
表示未找到父键的约束违规。
这意味着问题不是您尝试在子表中插入NULL
值,问题是父表不包含值为NULL
的行参考专栏。
PS:父表中的foreign key
子表也可能是primary key
(除非父表具有复合主键)。因此它不允许NULL
进入父表。
编辑1:在OP的问题中插入了其他信息。
此处发生的事件是childtablecolumn
包含NULL
个值,而父表的parenttablecolumn
不包含值为NULL
的单行。