如何处理jdbc事务中的父键约束?
我有 2 个表,分别名为 T1 和 T2。其中 T1 是父级,T2 是子级。 场景是,我启动了一个 jdbc 事务,然后在 T1 中插入一行,然后尝试在 T2 中插入一行。在 T2 中插入行会导致“完整性约束-未找到父键”异常。
我如何处理这种情况?
Connection con;
try{
con = ConnectionPool.getConnection();
con.setAutoCommit(false);
int T1Id = getNewId("T1"); // from sequence;
int T2Id = getNewId("T2"); // from sequence;
Insert in to table T1(t1Id,tName) values (T1Id,'A')
Insert in to table T2(t2Id, t1Id,tName) values (T2Id,T1Id,'A')//Here, Exception raises
con.commit();
}catch(Exception e){
try {con.rollback();} catch (SQLException e) {}
}finally{
try {con.setAutoCommit(true);} catch (SQLException e) {}
ConnectionPool.returnConnection(con);
}
使用JDBC API、struts1.2、Oracle10G数据库
I have 2 tables named T1 and T2. Where T1 is parent and T2 is child.
The scenario is, I started a jdbc transaction and then insert a row in T1 and then try to insert a row in T2. Inserting row in T2 gies me "Integrity Constraint-Parent key not found" exception.
How i handle this scenario ?
Connection con;
try{
con = ConnectionPool.getConnection();
con.setAutoCommit(false);
int T1Id = getNewId("T1"); // from sequence;
int T2Id = getNewId("T2"); // from sequence;
Insert in to table T1(t1Id,tName) values (T1Id,'A')
Insert in to table T2(t2Id, t1Id,tName) values (T2Id,T1Id,'A')//Here, Exception raises
con.commit();
}catch(Exception e){
try {con.rollback();} catch (SQLException e) {}
}finally{
try {con.setAutoCommit(true);} catch (SQLException e) {}
ConnectionPool.returnConnection(con);
}
Using JDBC API, struts1.2, Oracle10 G Database
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可能做错了什么。如果两个插入都在同一个事务中,则您刚才提到的情况就不会发生。请分享一些代码和更多信息(数据库服务器、表结构),看看我们是否可以帮助您。
You are probably doing something wrong. If both inserts are within the same transaction what you've just mentioned can't happen. Please share some code and more information (DB server, table structures) to see if we can help you.
您需要一个三步过程:
它应该是单个工作单元,因此使其具有事务性。
从你的伪代码中不可能看出。了解您是否使用自动生成的密钥也很有帮助。
我猜测您为 T1 假设的主键实际上并未出现。如果 T2 说外键不能为空或者是必需的,并且它没有出现在 T1 中,那么 RDBMS 系统应该抱怨并抛出异常。
You need a three step process:
It should be a single unit of work, so make it transactional.
It's impossible to tell from your pseudo code. It'd also be helpful to know whether or not you're using auto generated keys.
I'm guessing that the primary key you're assuming for T1 doesn't actually appear. If T2 says the foreign key cannot be null or is required, and it doesn't appear in T1, then the RDBMS system should complain and throw an exception.