// 每个数据库实体对象都会实现这个接口publicinterfaceEntity{StringgetId();voidsetId(Stringid);booleanisInserted();// 标记对象是新增的voidsetInserted(booleaninserted);booleanisUpdated();// 标记对象是更新的voidsetUpdated(booleanupdated);booleanisDeleted();// 标记对象是删除的voidsetDeleted(booleandeleted);/**
* Returns a representation of the object, as would be stored in the database.
* Used when deciding if updates have occurred to the object or not since it was last loaded.
*/// 持久化状态,当对象的属性没有改动时,不需要更新到数据库ObjectgetPersistentState();}
// 插入实体publicvoidinsert(Entityentity){// 分配 idif(entity.getId()==null){Stringid=dbSqlSessionFactory.getIdGenerator().getNextId();entity.setId(id);}// 加入缓存Class<?extendsEntity>clazz=entity.getClass();if(!insertedObjects.containsKey(clazz)){insertedObjects.put(clazz,newLinkedHashMap<String,Entity>());// order of insert is important, hence LinkedHashMap}insertedObjects.get(clazz).put(entity.getId(),entity);entityCache.put(entity,false);// False -> entity is inserted, so always changed// 设置为新增entity.setInserted(true);}
// 更新实体publicvoidupdate(Entityentity){entityCache.put(entity,false);// false -> we don't store state, meaning it will always be seen as changed// 设置为更新 entity.setUpdated(true);}
// 删除实体publicvoiddelete(Entityentity){// 添加缓存Class<?extendsEntity>clazz=entity.getClass();if(!deletedObjects.containsKey(clazz)){deletedObjects.put(clazz,newLinkedHashMap<String,Entity>());// order of insert is important, hence LinkedHashMap}deletedObjects.get(clazz).put(entity.getId(),entity);// 设置为删除entity.setDeleted(true);}
// 更新到数据库,此时事务还没有提交publicvoidflush(){// 有些更新对象可能标记删除了,所以需要删除determineUpdatedObjects();// Needs to be done before the removeUnnecessaryOperations, as removeUnnecessaryOperations will remove stuff from the cache// 有些新增对象可能标记删除了,所以需要删除removeUnnecessaryOperations();if(log.isDebugEnabled()){debugFlush();}// 执行 SQL 语句 flushInserts();flushUpdates();flushDeletes();}