GreenDao源码简要分析

GreenDao源码简要分析

1、AbstractDaoMaster抽象类的作用

AbstractDaoMaster 的主要作用为:

SQLiteDatabase相关操作: 所有Table 的创建、删除、升级
AbstractDao的信息获取和存储: AbstractDao主要作用就是提供操作Table的各种接口
AbstractDaoSession的创建 :创建AbstractDao,提供简单的操作表的接口

1.1、SQLiteDatabase的相关操作

Table的创建,删除,升级操作,是在AbstractDaoMaster子类DaoMaster里面实现的,代码很简单,不做过多解释,相关代码如下:

public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
        NoteDao.createTable(db, ifNotExists);
    }
public static void dropAllTables(SQLiteDatabase db, boolean ifExists) {
        NoteDao.dropTable(db, ifExists);
    }
public static class DevOpenHelper extends OpenHelper {
        public DevOpenHelper(Context context, String name, CursorFactory factory) {
            super(context, name, factory);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
            dropAllTables(db, true);
            onCreate(db);
        }
    }

1.2 AbstractDao的信息获取和存储

public DaoMaster(SQLiteDatabase db) {
        super(db, SCHEMA_VERSION);
        registerDaoClass(NoteDao.class);
    }
protected void registerDaoClass(Class> daoClass) {
        DaoConfig daoConfig = new DaoConfig(db, daoClass);
        daoConfigMap.put(daoClass, daoConfig);
    }

每个AbstractDao对应着一个DaoConfig,然后保存在Map< Class>, DaoConfig> daoConfigMap中,DaoConfig这个类的作用,一是通过反射的方式获取到AbstractDao对应的表名、表中所有字段(主键、非主键greendao中用Property对象来保存一个字段的信息)等相关信息,然后利用这些信息创建了辅助类TableStatements的一个实例,TableStatements这个类的作用是创建操作table的SQL语句;二是获取该表对应的缓存处理实例。DaoConfigTableStatements 的相关代码都很简单,这里不再贴出来了。

1.3 AbstractDaoSession:创建AbstractDao,提供简单的操作表的接口

AbstractDaoSession的作用,一是提供获取AbstractDao的接口,从而操作各个表:

DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();

这里为啥子要通过AbstractDaoSession来创建AbstractDao然后提供给client端使用,而不是直接在AbstractDaoMaster创建出AbstractDao然后提供给client端使用呢?看AbstractDaoSession里面也提供了操作数据库的简单接口(当然最终都是通过对应的AbstractDao来完成的),难道就为了这个玩意?????

2、table操作

理清了关键几个类的作用后,下面分析table的相关操作就比较简单了。

2.1 insert 操作

通过DaoConfig获取到TableStatements,然后由TableStatements得到SQLiteStatement

public long insert(T entity) {// statements = config.statements;
        return executeInsert(entity, statements.getInsertStatement());
    }
public SQLiteStatement getInsertStatement() {
        if (insertStatement == null) {
            String sql = SqlUtils.createSqlInsert("INSERT INTO ", tablename, allColumns);
            insertStatement = db.compileStatement(sql);
        }
        return insertStatement;
    }

根据表名、字段生成一条SQL语句

public static String createSqlInsert(String insertInto, String tablename, String[] columns) {
        StringBuilder builder = new StringBuilder(insertInto);
        builder.append('"').append(tablename).append('"').append(" (");
        appendColumns(builder, columns);
        builder.append(") VALUES (");
        appendPlaceholders(builder, columns.length);
        builder.append(')');
        return builder.toString();
    }

执行insert操作

private long executeInsert(T entity, SQLiteStatement stmt) {
        long rowId;
        if (db.isDbLockedByCurrentThread()) {// database被当前线程给锁住了
            synchronized (stmt) {
                bindValues(stmt, entity);
                rowId = stmt.executeInsert();
            }
        } else {
            // Do TX to acquire a connection before locking the stmt to avoid deadlocks
            db.beginTransaction();
            try {
                synchronized (stmt) {
                    bindValues(stmt, entity);
                    rowId = stmt.executeInsert();
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }
        updateKeyAfterInsertAndAttach(entity, rowId, true);
        return rowId;
    }

给操作的bean更新字段_id的值

protected void updateKeyAfterInsertAndAttach(T entity, long rowId, boolean lock) {
        if (rowId != -1) {
            K key = updateKeyAfterInsert(entity, rowId);
            attachEntity(key, entity, lock);
        } else {
            // TODO When does this actually happen? Should we throw instead?
            DaoLog.w("Could not insert row (executeInsert returned -1)");
        }
    }

缓存操作:IdentityScope键值对,key为表中主键,value为bean

protected final void attachEntity(K key, T entity, boolean lock) {
        attachEntity(entity);
        if (identityScope != null && key != null) {
            if (lock) {
                identityScope.put(key, entity);
            } else {
                identityScope.putNoLock(key, entity);
            }
        }
    }

2.2 query操作

public T load(K key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }
        if (identityScope != null) {// 如果有缓存,直接从缓存中取值
            T entity = identityScope.get(key);
            if (entity != null) {
                return entity;
            }
        }
        String sql = statements.getSelectByKey();
        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);
        return loadUniqueAndCloseCursor(cursor);
    }

你可能感兴趣的:(GreenDao源码简要分析)