2011-05-19 46 views
9

创建我有我的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

任何帮助,非常感谢!

问候, 哈哥

回答

5

你错过了一些用于返回更新的ID,你必须这样做:

Long hageId = null; 

try { 
    result = insertTable1.executeUpdate(); 
} catch (Throwable e) { 
    ... 
} 

ResultSet rs = null; 

try { 
    rs = insertTable1.getGeneratedKeys(); 
    if (rs.next()) { 
     hageId = rs.getLong(1); 
    } 
... 
+0

谢谢!它现在完美。但是我仍然不清楚:在我运行代码之前,我的表格是空的。因此'exececuteUpdate'返回了受影响的行数(在本例中为1),这也是生成的ID。我认为这也应该起作用 - 它也会在第二次运行中引发异常......或者'getGeneratedKeys()'使密钥可用? – hage 2011-05-19 12:36:07

+0

插入的行ID从最后一行开始+1,除非你在表格上做了'truncate',它不会初始化为0. – EricParis16 2011-05-21 17:50:42

+0

+1我正在长时间看这个答案 – 2013-07-03 11:27:08

1

代替使用的executeUpdate的()的使用执行(),然后返回主键。

http://www.coderanch.com/t/301594/JDBC/java/Difference-between-execute-executeQuery-executeUpdate

但我不使用DB工作...所以我可以做一个错误

+0

我知道不同的execute *()方法之间的区别。我只是想以错误的方式得到钥匙。我认为在设置'Statement.RETURN_GENERATED_KEYS'时,executeUpdate()会返回键值而不是已更改的行数。不过谢谢你的回答。 – hage 2011-05-19 13:58:54