2017-07-02 31 views
0

我遇到了將我的模型類添加到房間數據庫的問題。我已閱讀@Relation,@Embedded,但我無法弄清楚如何處理模型類。Android室數據庫。如何將我的模型類添加到房間數據庫

在這裏,我的模型類來自服務器。我需要存儲這些數據

public class ResultsItem { 

private String model; 
private int id; 
private int distanceLon; 
private String brand; 

//*PROMBLEM HERE* 
private List<BidsItem> bids; 

//*PROMBLEM HERE* 
private User user; 

//*PROMBLEM HERE* 
private List<FotosItem> fotos; 


// getters/setters... 

} 

FotosItem類

public class FotosItem { 
private String imageUrl; 
private int resultItemId; 
private int id; 

//getters/setters 

} 

BidsItem類

public class BidsItem { 
private double distanceToAuto; 
private boolean isWin; 
private int sum; 
private String currency; 
private int id; 

//getters/setters 

} 

我會很感激,如果有人告訴我,我需要做的,或者至少在什麼方向移動

+0

如果你想在數據庫中保存一個類,你必須將它轉換成一個字節數組(apache commons lang有一個工具,但你可以自己創建它,如果你喜歡它),然後你使用blob字段將其放入數據庫中。使用getBlob加載它並使用apache lang將字節流轉換回類 – Zoe

+0

@LunarWatcher thx以獲得快速評論,但我還需要使用'LiveData <>'獲取已添加到Room數據庫的新數據。這些數據來自服務器,當分頁數據的下一部分 – kovac777

+0

嗯,嗯,我們不能真正幫助你,因爲我們不知道'BidsItem','User'或者'FotosItem'是什麼。我們不知道'ResultsItem'和這些其他事物之間關係的性質(例如,'User'是否有一個'ResultsItem'或N個可能的'ResultItem'實例)?很可能,所有這些都是實體,並且您需要根據您擁有的關係類型來確定外鍵的位置。忽略'@ Relation'。如果'ResultsItem'和'User'之間存在純1:1關係,'User'最多可能是'@ Embedded'。 – CommonsWare

回答

0

你可以通過在DAO類中做一些tweek來實現它。使用忽略註釋列表。

public class ResultsItem { 

private String model; 
private int id; 
private int distanceLon; 
private String brand; 

@Ignore 
private List<BidsItem> bids; 

private User user; 

@Ignore 
private List<FotosItem> fotos; 


// getters/setters... 

} 

FotosItem類

public class FotosItem { 
private String imageUrl; 
private int resultItemId; 
private int id; 

//getters/setters 

} 

BidsItem類

public class BidsItem { 
private double distanceToAuto; 
private boolean isWin; 
private int sum; 
private String currency; 
private int id; 

//getters/setters 

} 

現在DAO類

@Dao 
public abstract class DBAccess { 

@Insert 
public abstract void insertBids(List<BidsItem> pets); 

@Insert 
public abstract void insertFotos(List<FotosItem> pets); 

@Insert 
public abstract void insertResultItem(ResultsItem resultItem); 

public void insertResultWithBidsFotos(ResultsItem resultItem) { 
     insertBids(resultItem.getBids()); 
     insertFotos(resultItem.getFotos()); 
     insertResultItem(resultItem); 
    } 

} 

同樣你可以實現檢索。

相關問題