<p>例如:下面几行代码:</p>
<p>sqlMapClient.startBatch();<br>sqlMapClient.insert("Account.insert", account);<br>order.setAccountId(account.getAccountId()); // error!<br>sqlMapClient.insert("Order.insert", order);<br>sqlMapClient.executeBatch();</p>
<p>在插入account之后,使用系统自动产生的accountid插入到order记录里。看上去一切都没有问题,但是却会产生错误。</p>
<p>错误的原因在于:</p>
<p>首先ibatis中的sql语句产生方式都是在运行之前提前生成的,所以运行到第二句的时候,会生成类似于insert accout 。。。。。之类的语句,运行到第三句的时候会将null值赋值给order的accoundid语句,当运行到第四句的时候,会运行insert语句insert order。。。。。accountid=null。此时出错。</p>
<p>要理解这个错误产生的原因必须要搞清楚:</p>
<p> 1,sql语句在运行之前,提前产生</p>
<p> 2,在executeBatch之前,不会有任何sql语句产生</p>
<p>sqlMapClient.startBatch();<br>sqlMapClient.insert("Account.insert", account);<br>order.setAccountId(account.getAccountId()); // error!<br>sqlMapClient.insert("Order.insert", order);<br>sqlMapClient.executeBatch();</p>
<p>在插入account之后,使用系统自动产生的accountid插入到order记录里。看上去一切都没有问题,但是却会产生错误。</p>
<p>错误的原因在于:</p>
<p>首先ibatis中的sql语句产生方式都是在运行之前提前生成的,所以运行到第二句的时候,会生成类似于insert accout 。。。。。之类的语句,运行到第三句的时候会将null值赋值给order的accoundid语句,当运行到第四句的时候,会运行insert语句insert order。。。。。accountid=null。此时出错。</p>
<p>要理解这个错误产生的原因必须要搞清楚:</p>
<p> 1,sql语句在运行之前,提前产生</p>
<p> 2,在executeBatch之前,不会有任何sql语句产生</p>