1

首先,我会尝试描述我愿意做什么,然后,我会问我的问题。我需要执行以下操作:

  • 列出与某些条件对应的所有行
  • 做一些测试(例如:检查它是否尚未插入),如果测试通过,则将行插入另一个数据库
  • 删除行(是否通过测试)

以下是我的实现

List<MyObject> toAdd = new ArrayList<MyObject>();
for(MyObject obj:list){
    if(!notYetInserted(obj){
        toAdd.add(obj);
    }
}
myObjectDAO.insertList(toAdd);
myObjectDAO.deleteList(list);

服务方法被标记为事务性的。

在我的 DAO 中,deleteList 和 insertList 的方法非常相似,所以我将在这里放置插入方法。

public void insertList(final List<MyObject> list){
String sql = "INSERT INTO table_test " +
    "(col_id, col2, col3,col4) VALUES (?, ?, ?,?)";

List<Object[]> paramList = new ArrayList<Object[]>();

for (MyObject myObject : list) {
    paramList.add(new Object[] {myObject.getColId(), 
        myObject.getCol2(), myObject .getCol3(), myObject.getCol4()}
    );
}
simpleJdbcTemplate.batchUpdate(sql, paramList);        

}

我不确定执行此类操作的最佳方法,我在这里读到,在循环内调用更新可能会减慢系统速度(特别是在我的情况下,我一次将有大约 100K 插入/删除)。我想知道 DAO 中的这些额外循环是否不会进一步减慢我的系统,如果在处理该批次时反复发生问题会发生什么(我还考虑将测试从服务移动到 DAO,以便只有一个循环和一个额外的测试,我真的不知道这是否是个好主意)。所以,我想听听你的建议。非常感谢。

PS:如果您需要更多详细信息,请随时询问!

4

1 回答 1

1

This is not necessarily a bad approach, but you are right, it might be really slow. If I were to do a process like this that inserted or deleted this many rows I would probably do it all in a stored procedure. My code would just execute the proc and the proc would handle the list and the enumeration through it (as well as the inserts and deletes).

于 2012-09-25T14:37:42.240 回答