2012-03-07 35 views
0

我有经典设置ibatis的插入父/子关系

public class Parent { 
     String name; 
     Collection<Child> children; 

    private class child{ 
     string name; 
    } 
} 

现在我要插入父第一属性父表,比获得ID,最后店子records.whats实现的最佳途径在ibatis中是一样的吗?

回答

0

您可以为例如使用iBatis(我使用的是iBatis版本2.3.4,所以这个例子是基于这个的)。创建一批语句可以提高性能。同样重要的是要注意将这个批处理包装在一个单独的事务中,就好像它没有被包装一样,然后每个语句将启动一个新的事务(性能可能是一个问题,这取决于我认为的批量大小)。

请参阅下面的示例。您会注意到批次startBatch()的开始仅在父记录更新或插入后才开始。这是因为在调用executeBatch()之前,不会生成数据库生成的密钥。这意味着如果您使用selectKey更新您的对象与生成的键,他们将返回null。这就是为什么创建/更新父记录在startBatch()声明之前。希望这有助于你作为一个例子。

try { 
    sqlMap.startTransaction(); 

    if (parent.getId == null) { 
     sqlMap.insert("createParent", parent); 
    } else { 
     sqlMap.update("updateParent", parent); 
    } 

    sqlMap.startBatch(); 
    for (final Child exapleChild: parent.getChildren()) { 
     exapleChild.setParentId(parent.getId); 
     sqlMap.insert("createChildForParent", objectReference1); 
    } 
    sqlMap.executeBatch(); 
    sqlMap.commitTransaction(); 
} catch (final SQLException e) { 
    throw new XXXException(e); 
} finally { 
    try { 
     sqlMap.endTransaction(); 
    } catch (SQLException e) { 
     throw new XXXException(e); 
    } 
}