2016-11-05 56 views
0

我正在保存處於一對多關係的數據。像國內擁有衆多的狀態,如下在Android中插入與sqlite的一對多關係

圖像這裏是模型db表是建立在 Hint as to what the sqlite db table looks like

public class Country { 

    private int countryId; 

    private String countryName; 

    private List<State> states; 
} 

,這裏是國家和狀態保存代碼。

public void saveToDb(List<Country> countries) { 

    for(Country country: countries){ 
     saveCountry(country); 

     List<State> states = country.getStates(); 

     for(State state :states) 
      saveState(state); 
    } 
} 

瞭解嵌套循環多麼昂貴都可以,我想知道是否有保存該的有效方式,而不使用嵌套循環的數據。 任何幫助將是非常讚賞

回答

1

你可以做批量插入:

db.beginTransaction(); 
for (Country country: countries) { 
    saveCountry(country); 
    List<State> states = country.getStates(); 

    for(State state :states) 
     saveState(state); 
} 
db.setTransactionSuccessful(); 
db.endTransaction(); 

把你db.beginTransaction();db.setTransactionSuccessful();db.endTransaction();外循環。

+0

想法是隻使用一個for循環,只用一個循環保存國家和州, –

+0

將begintransaction,settransaction和end事務放在循環之外,可以提高性能。在我看來,循環可以在設備中快速運行,每個循環中發生的事務是性能較差的原因。你可以參考這個stackoverflow答案http://stackoverflow.com/questions/3501516/android-sqlite-database-slow-insertion – MinFu