近期因?yàn)樾枰镜鼐彺嬉恍?shù)據(jù),故使用到了第三方框架GreenDao,該框架的使用方法在此不做贅述,此篇只記錄使用greendao過程中遇到的坑(后續(xù)使用中如果遇到其他問題再進(jìn)行更新)。
1.調(diào)用自動(dòng)生成的dao對(duì)象的update方法后無效:
調(diào)用update方法后,再獲取數(shù)據(jù)庫(kù)中的數(shù)據(jù)仍會(huì)取到更新前的數(shù)據(jù)。該現(xiàn)象是因?yàn)間reendao自帶的緩存機(jī)制并不會(huì)隨著調(diào)用update方法后及時(shí)進(jìn)行更新,所以在調(diào)用update方法后,需要調(diào)用detachAll方法進(jìn)行緩存的刪除。
public void updateLocation(WeatherLocation weatherLocation) {
mWritableDao.update(weatherLocation);
//更新后刪除緩存數(shù)據(jù)庫(kù)信息
mWritableDao.detachAll();
}
2.在對(duì)被注釋了@Entity的實(shí)體類進(jìn)行修改后(新增、刪除該實(shí)體類中的變量),重新運(yùn)行程序后在使用greendao的地方會(huì)報(bào)找不到相關(guān)字段的sql語句錯(cuò)誤:
greendao只會(huì)在程序初始化之后自動(dòng)生成@Entity實(shí)體類的相關(guān)表,在app進(jìn)行更新后并不會(huì)根據(jù)@Entity實(shí)體類的更新而去重新構(gòu)建相關(guān)表類,解決該問題的方法為卸載后重新安裝app。但是一方面在實(shí)際開發(fā)過程中,經(jīng)常會(huì)對(duì)要緩存的實(shí)體類中的字段進(jìn)行增刪,另一方面在版本更新后讓用戶卸載再安裝體驗(yàn)太差。所以在此提供一個(gè)存儲(chǔ)思路:對(duì)于要緩存的對(duì)象,在進(jìn)行緩存前將該實(shí)體類進(jìn)行json轉(zhuǎn)換,把該對(duì)象轉(zhuǎn)換成string字符串,再將該字符串作為@Entity實(shí)體類中的string字段進(jìn)行緩存,@Entity實(shí)體類中的變量即可固定成數(shù)據(jù)庫(kù)id、string字符串
@Entity
public class WeatherLocationTotal {
@Id(autoincrement = true)
private Long dbid;
private String json;
@Generated(hash = 197335340)
public WeatherLocationTotal(Long dbid, String json) {
this.dbid = dbid;
this.json = json;
}
@Generated(hash = 1000997541)
public WeatherLocationTotal() {
}
public Long getDbid() {
return this.dbid;
}
public void setDbid(Long dbid) {
this.dbid = dbid;
}
public String getJson() {
return this.json;
}
public void setJson(String json) {
this.json = json;
}
如此,只要在取出json字段后再進(jìn)行一次json轉(zhuǎn)對(duì)象的操作就可以完成對(duì)象存儲(chǔ),解決上述問題。這里只提供一個(gè)思路,具體json如何轉(zhuǎn)實(shí)體類以及實(shí)體類如何轉(zhuǎn)json,網(wǎng)上資料不少,不再進(jìn)行贅述