我目前正在跟踪应用中某些对象的个别更改。通过将当前对象(由用户修改的副本)与数据库中的内容进行比较,这已经可以正常工作。
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;
}
为了解决这个性能瓶颈,我现在直接使用greenDAO返回的对象,而不创建副本。这使得列表加载速度更快,但现在我无法再跟踪更改。当我尝试将当前对象与数据库中的对象进行比较时,我的查询返回已修改的对象(正如预期的会话缓存一样)。
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);
}
我不想禁用会话缓存,因为性能提升很重要。我也不想用daoSession.clear()
清除它,因为上面的代码经常运行,并且必须一直重建缓存,使性能改进无效。
那么,有没有办法忽略单个查询的会话缓存?或者以某种方式要求新对象而不是现有引用?
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();
}
当我从数据库中查询对象以与其用户修改状态进行比较时,我希望能够接收与数据库中持久存在的新对象完全相同,而不是对之前加载的对象的引用。这有可能吗?