Android 在greenDAO中有一个查询忽略会话缓存
我目前跟踪应用程序中某些对象的个别更改。通过将当前对象(用户修改过的副本)与数据库中的对象进行比较,这已经很好地工作了Android 在greenDAO中有一个查询忽略会话缓存,android,greendao,Android,Greendao,我目前跟踪应用程序中某些对象的个别更改。通过将当前对象(用户修改过的副本)与数据库中的对象进行比较,这已经很好地工作了 public void syncChanges(GsonTask current, GsonTask old) { // Load previous version of object if not provided. if (old == null) { // Here I get the old object from the databas
public void syncChanges(GsonTask current, GsonTask old) {
// Load previous version of object if not provided.
if (old == null) {
// Here I get the old object from the database, while the user modified one is not touched.
old = TasksService.getInstance().loadTask(current.getId());
}
// Bunch of logic to compare the current and old objects and track changes...
// Another bunch of logic to sync the changes found to the server.
// Save the current state of the object to the database (replacing the old one).
TasksService.getInstance().saveTask(current);
}
但是这种方法会带来性能问题,因为我需要复制从greenDAO获得的对象,以便以后能够比较它们。因此,本质上,我并没有利用会话缓存,因为新对象(副本)总是在查询之后创建的
public List<GsonTask> loadAllTasks() {
// Load data from greenDAO and create the user modifiable copies.
return gsonFromTasks(mExtTaskDao.listAllTasks());
}
private List<GsonTask> gsonFromTasks(List<Task> tasks) {
List<GsonTask> gsonTasks = new ArrayList<GsonTask>();
if (tasks != null) {
// Create the copies.
for (Task task : tasks) {
gsonTasks.add(new GsonTask(...));
}
}
return gsonTasks;
}
当我从数据库中查询对象以与其用户修改的状态进行比较时,我希望能够接收一个新对象,而不是对以前加载的对象的引用。这有可能吗?显然我不允许在这里重复我的答案,但请参阅stackoverflow.com/a/47401143/2775083上关于为什么会发生这种行为的我的答案
public List<Task> loadAllTasks() {
List<Task> tasks = mExtTaskDao.listAllTasks();
// Return the greenDAO objects directly, without creating copies.
return tasks != null ? tasks : new ArrayList<Task>();
}
public void syncChanges(GsonTask current, GsonTask old) {
if (old == null) {
// Here I can no longer load the previous state of this object (i.e. what's actually persisted in the database).
// old is now just a reference to current.
old = TasksService.getInstance().loadTask(current.getId());
}
// Comparison between the user modified object and what's in the database can't happen, as both objects are the same.
// I get sad. :/ Syncing changes is no longer possible.
// Saving the current state of the object still works, as expected.
TasksService.getInstance().saveTask(current);
}
public Task selectTask(Long id) {
// Here I'd like to receive a new object, not the existing reference.
return mDao.queryBuilder().where(TaskDao.Properties.Id.eq(id)).unique();
}