2014-09-02 36 views
1

我正在解析一個JSON文件以使用OrmLite在數據庫中生成行和關係。使用以下代碼,解析所有內容大約需要20多分鐘。有什麼辦法可以優化這個以縮短時間嗎?優化OrmLite多對多代碼

我有3個表組成一個多到多的關係。

public class FirstTable { 
    int id; 
    ForeignCollection<IntermediateTable> intermediateTables; 
} 

public class IntermediateTable { 
    int id; 
    FirstTable firstTable; 
    SecondTable secondTable; 
} 

public class SecondTable { 
    int id; 
    ForeignCollection<IntermediateTable> intermediateTables; 
} 

創建和填充第一和第二表之後,我解析一個JSON文件來創建FirstTable和SecondTable之間的關係。 JSON文件存儲FirstTable對象的集合和相關的SecondTable條目的ID。

我的代碼看起來是這樣的:

setForeignRelations(JSONObject jsonObject, FirstTable firstTable) { 

    JSONArray secondTables = jsonObject.getJSONArray(SECOND_TABLE_KEY); 

    for (int i = 0; i < secondTables.length(); i++) { 
     int secondTableId = ((Integer)secondTables.get(i)).intValue(); 

     SecondTable secondTable = DbManager.getInstance().getHelper().getSecondTableDao().queryForId(secondTableId); 

     IntermediateTable intermediateTable = new IntermediateTable(); 

     intermediateTable.setFirstTable(firstTable); 
     intermediateTable.setSecondTable(secondTable); 

     DbManager.getInstance().getHelper().getIntermediateTableDao().create(intermediateTable); 
    } 
} 

回答

0

我從來沒有嘗試,但這樣可能會更快,應該工作:

setForeignRelations(JSONObject jsonObject, FirstTable firstTable) { 

JSONArray secondTables = jsonObject.getJSONArray(SECOND_TABLE_KEY); 

for (int i = 0; i < secondTables.length(); i++) { 
    int secondTableId = ((Integer)secondTables.get(i)).intValue(); 

    IntermediateTable intermediateTable = new IntermediateTable(); 

    intermediateTable.setFirstTable(firstTable); 
    intermediateTable.setSecondTable(new SecondTable(secondTableId)); 

    DbManager.getInstance().getHelper().getIntermediateTableDao().create(intermediateTable); 
} 

}

這應該工作,因爲它只會將第二表的id保存在intermediateTable中。所以你不需要請求數據庫來填充第二個表的所有字段。

如果你想再次更快,你可以看看這裏,加速您的對象插入: ORMLite's createOrUpdate seems slow - what is normal speed?

所以,你將使用callBatchTasks方法,允許增加速度ORMLite。

有了這兩件事,你可以提高SELECT的速度(因爲你不再這樣做了)以及使用callBatchTasks方法的INSERT。

如果你想callBatchTasks方法的一個例子。你可以看看這裏: Android ORMLite slow create object

+0

這工作。謝謝! – 2014-09-10 17:39:40