创建我有我的MySQL数据库,并进行了这样的创建两个表:JDBC:在PK外键在同一交易
CREATE TABLE table1 (
id int auto_increment,
name varchar(10),
primary key(id)
) engine=innodb
和
CREATE TABLE table2 (
id_fk int,
stuff varchar(30),
CONSTRAINT fk_id FOREIGN KEY(id_fk) REFERENCES table1(id) ON DELETE CASCADE
) engine=innodb
(这些都不是原始表。关键是table2有一个外键引用表1中的主键)
现在在我的代码中,我想添加条目到一个事务中的两个表。所以我设置autoCommit
为false:
Connection c = null;
PreparedStatement insertTable1 = null;
PreparedStatement insertTable2 = null;
try {
// dataSource was retreived via JNDI
c = dataSource.getConnection();
c.setAutoCommit(false);
// will return the created primary key
insertTable1 = c.prepareStatement("INSERT INTO table1(name) VALUES(?)",Statement.RETURN_GENERATED_KEYS);
insertTable2 = c.prepareStatement("INSERT INTO table2 VALUES(?,?)");
insertTable1.setString(1,"hage");
int hageId = insertTable1.executeUpdate();
insertTable2.setInt(1,hageId);
insertTable2.setString(2,"bla bla bla");
insertTable2.executeUpdate();
// commit
c.commit();
} catch(SQLException e) {
c.rollback();
} finally {
// close stuff
}
当我执行上面的代码,我得到一个异常:
MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
看来我以前犯类似的主键是不是在交易中使用。
我在这里错过了什么吗?我真的认为生成的主键应该在事务中可用。
程序上的Glassfish 3.0.1运行使用MySQL的连接器5.1.14和MySQL 5.5.8
任何帮助,非常感谢!
问候, 哈哥
谢谢!它现在完美。但是我仍然不清楚:在我运行代码之前,我的表格是空的。因此'exececuteUpdate'返回了受影响的行数(在本例中为1),这也是生成的ID。我认为这也应该起作用 - 它也会在第二次运行中引发异常......或者'getGeneratedKeys()'使密钥可用? – hage 2011-05-19 12:36:07
插入的行ID从最后一行开始+1,除非你在表格上做了'truncate',它不会初始化为0. – EricParis16 2011-05-21 17:50:42
+1我正在长时间看这个答案 – 2013-07-03 11:27:08