2013-10-07 28 views
0

數據庫我有一個讀者在Java中: 與讀者(Reader read)從文件用線條保存文件的讀者在Java中

的1'000.000,我需要保存每一行中我的數據庫,我讀的閱讀器,如:

  int data = read.read(); 
      String line = ""; 


      while (data != -1) { 
       char dataChar = (char) data; 
       data = read.read(); 
       if (dataChar != '\n') { 
        line = line + dataChar; 
       } else { 
        i++; 
        showline(line); 
        line = ""; 
       } 
      } 

話,我打電話給我的DAO的每一行:

private static void showline(String line) { 
    try { 
     if (line.startsWith(prefix)) { 
      line = line.substring(prefix.length()); 
     } 
     ms = new Msisdn(Long.parseLong(line, 10), idList); 
     ListDAO.createMsisdn(ms); 
    } catch (Exception e) { 
    } 
} 

我的DAO是:

public static void createMsisdn(Msisdn msisdn) { 
    EntityManager e = DBManager.createEM(); 
    try { 
     createMsisdn(msisdn, e); 
    } finally { 
     if (e != null) { 
      e.close(); 
     } 
    } 

} 

public static void createMsisdn(Msisdn msisdn, EntityManager em) { 

    em.getTransaction().begin(); 
    em.persist(msisdn); 
    em.getTransaction().commit(); 

} 

但是我的問題是,用1'000.000行的文件大約需要1小時30分鐘才能完成。我怎樣才能讓它更快?

(我的主要問題是調用DAO 1'000.000次,因爲它非常慢,因爲一段時間更快,沒有調用DAO的時間小於1分鐘,但是調用DAO的時間爲2小時)

+0

如果你能做到這一點所有在單個事務中,它可能會更快或作爲批處理 – MadProgrammer

+0

但我怎樣才能只在一個交易中多行的數據庫上傳嗎? – user2768380

+0

您的所有代碼都說明了基本想法。您需要一些方法來啓動,提交或回滾DAO中的事務 – MadProgrammer

回答

0

讀取字符並通過一個其附加到String一個是難以置信的效率低下。使用BufferedReader閱讀的文本行要好得多:

 String line; 
     BufferedReader reader = new BufferedReader(read); 
     while ((line = reader.readLine()) != null) { 
      showline(line); 
     } 

這不會有你的情況有很大的影響,但:你將在一個單獨的事務的每一行,並且每次交易都能拿幾百毫秒去完成。您應該以可以在單個事務中插入多行的方式來構建代碼。例如,你可以這樣寫行的塊,但你必須改變showlinescreateMsisdn方法,使他們接受在一個時間數和單批處理它們:

 final int TRANSACTION_SIZE = 500; 
     int i = 0; 
     String[] lines = new String[TRANSACTION_SIZE]; 
     BufferedReader reader = new BufferedReader(read); 
     while ((lines[i] = reader.readLine()) != null) { 
      if (i >= lines.length) { 
       showlines(lines, lines.length); 
       i = 0; 
      } else { 
       i++; 
      } 
     } 

     if (i > 0) showlines(lines, i);