2015-08-13 22 views
0

巨大的byte []的問題,我有2個表頭和二進制如何解決OrmLite

頁眉是水木清華這樣的:

@DatabaseTable(tableName = Header.TABLE_NAME) 
public class Header extends Table { 
    @DatabaseField(
      generatedId = true, 
      columnName = HEADER_ID, 
      dataType = DataType.LONG_OBJ 
    ) 
    private Long id; 

    @ForeignCollectionField(orderColumnName = Binary.BINARY_ORDER, orderAscending = true) 
    private Collection<Binary> binaries=new ArrayList<Binary>(); 
} 

和二進制代碼是:

@DatabaseTable(tableName = Binary.TABLE_NAME) 
public class Binary { 
    @DatabaseField(
      generatedId = true, 
      columnName = BINARY_ID, 
      dataType = DataType.LONG_OBJ) 
    private Long id; 

    @DatabaseField(
      columnName = BINARY_HEADER_ID, 
      foreign = true, 
      foreignAutoCreate = true, 
      foreignAutoRefresh = true, 
      //uniqueCombo = true, 
      canBeNull = false, //there always must be a link to Item._ID 
      columnDefinition = "integer constraint fk_4 references `"+ Header.TABLE_NAME+"`(`"+ Header.HEADER_ID+"`) on delete cascade" 
    ) 
    private Header header=null; 

    @DatabaseField(
      columnName = BINARY_ORDER, 
      //uniqueCombo = true, 
      canBeNull = false, 
      dataType = DataType.INTEGER_OBJ, 
      defaultValue = "0" 
    ) 
    private Integer order =0; 

    @DatabaseField(
      columnName = BINARY_CHUNK, 
      dataType = DataType.BYTE_ARRAY) 
    private byte[] chunk=null; 
} 

我的問題是在byte[] chunk字段中,由於每個塊的大小爲1MB種類,並且它們的數量幾乎是無限的,所以當我將讀取Header記錄時,OrmLite將隱含地讀取Collection<Binary>包含大量內容的列表 - 因此可能導致內存耗盡。

我應該如何聲明我的表來克服這個問題?

+1

*如何解決OrmLite *中的巨大字節[]問題:不使用巨大字節[] – Selvin

+0

請閱讀問題。我沒有使用巨大的'byte []' - 而是'byte []'的列表,而這可能是巨大的 – barmaley

+0

仍然沒有使用它......根本不存儲BLOB,而是參考文件......如果OrmLite支持延遲加載 - 使用它...無論如何,這是[ORMs不好]的很多原因之一(http://www.tonymarston.net/php-mysql/object-relational-mappers-are-evil.html) ... – Selvin

回答

1

首先聲明您的收藏懶惰和借鑑國外集合:

@ForeignCollectionField(orderColumnName = Binary.BINARY_ORDER, orderAscending = true, eager=false) 
private ForeignCollection<Binary> binaries; //to be able to retrieve CloseableIterator 

如何遍歷數據:數據加載懶洋洋地意味着一個連接保持,以確保數據從而獲取了iterator.close();

CloseableIterator<Binary> iterator = binaries.closeableIterator(); 
    try { 
     while(iterator.hasNext()){ 
     Binary bin= iterator.next(); 
     //do stuff 
     bin.setChunk(null) //discard if not needed any more 
     } 
    } finally { 
     // must always close our iterators otherwise connections to the database are held open 
     iterator.close(); 
    } 

這只是一個提示,因爲我不知道你將如何處理數據,但你的代碼應該看起來像這樣。

+1

Thanx - 你的答案是相當豐富。此外,我會自己做:) – barmaley