我有一个RealmObject,它仅用作临时数据缓存(会有很多条目)。我还编写了一个静态方法add()
,因此可以轻松添加一个新条目,但这似乎太复杂了。这是整个班级:
public class ExchangePairPriceCache extends RealmObject {
@Index
private String exchangeName;
@Index
private String baseCurrency;
@Index
private String quoteCurrency;
private float price;
private long lastPriceUpdate;
public ExchangePairPriceCache() {
exchangeName = "";
baseCurrency = "";
quoteCurrency = "";
price = 0;
lastPriceUpdate = 0;
}
public ExchangePairPriceCache(String exchangeName, String baseCurrency, String quoteCurrency) {
this.exchangeName = exchangeName;
this.baseCurrency = baseCurrency;
this.quoteCurrency = quoteCurrency;
price = 0;
lastPriceUpdate = 0;
}
public void setPrice(float price) {
// this needs to be called inside a Realm transaction if it's a managed object
this.price = price;
lastPriceUpdate = System.currentTimeMillis();
}
public float getPrice() {
return price;
}
/* static functions */
public static void add(String exchangeName, String baseCurrency, String quoteCurrency, float price) {
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(r -> {
ExchangePairPriceCache priceCache = r.where(ExchangePairPriceCache.class)
.equalTo("exchangeName", exchangeName)
.equalTo("baseCurrency", baseCurrency)
.equalTo("quoteCurrency", quoteCurrency).findFirst();
if(priceCache != null) {
priceCache.setPrice(price);
} else {
priceCache = new ExchangePairPriceCache(exchangeName, baseCurrency, quoteCurrency);
priceCache.setPrice(price);
ExchangePairPriceCache finalPriceCache = priceCache;
r.insert(finalPriceCache);
}
});
realm.close();
}
public static ExchangePairPriceCache get(String exchangeName, String baseCurrency, String quoteCurrency) {
Realm realm = Realm.getDefaultInstance();
ExchangePairPriceCache priceCache = realm.where(ExchangePairPriceCache.class)
.equalTo("exchangeName", exchangeName)
.equalTo("baseCurrency", baseCurrency)
.equalTo("quoteCurrency", quoteCurrency)
.greaterThan("lastPriceUpdate", System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(10)).findFirst();
if(priceCache != null)
priceCache = realm.copyFromRealm(priceCache);
realm.close();
return priceCache;
}
public static void deleteAll() {
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(r -> r.delete(ExchangePairPriceCache.class));
realm.close();
}
}
问题:
ExchangePairPriceCache.add("NASDAQ", "AAPL", "USD", 100.5);
之类的缓存中,并在需要时使用ExchangePairPriceCache.deleteAll()
删除所有条目。add()
函数?现在,我检查条目是否已经存在,然后更新价格,如果不存在,我创建一个新对象并将其插入Realm。我无法使用updateOrInsert
,因为我没有对象的唯一索引。也许我只是问自己太多了,这一切都很好。但我真的很感谢每天使用它的专家的一些意见。
答案 0 :(得分:1)
您应该将“存储库设计模式”与DAO对象(数据访问对象)一起使用,以进行所有读/写事务。
模型类应该是仅保留实体的对象的盲目副本。
由于您没有唯一的标识符,因此可以在下面尝试