[Android]GreenDao(1)--項目配置

項目配置

  • grdle配置

    在Android Studio的gradle配上

    compile ‘de.greenrobot:greendao:1.3.7’
    compile ‘de.greenrobot:greendao-generator:1.3.1’

  • 項目配置

項目示例1

注意,src-gen是我們新建一個文件夾,用來放GreenDao生成的文件

項目示例2

未完成該步驟之前,src-gen是空文件夾,我們需要新建一個包,在該包下新建一個Java文件,做初始化工作。
如圖所示,我創建了名爲’com.usst.chensl.introducdemo.db’的包,和名爲’ExampleDaoGenerator’的Java文件。

ExampleDaoGenerator文件如下

package com.usst.chensl.introducdemo.db;

import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;

/**
 * 初始化工作
 * Created by ChenSL on 2015/8/14.
 */
public class ExampleDaoGenerator {


    private static void addTaskDetail(Schema schema) {
        //指定實體類
        Entity entity = schema.addEntity("User");
        //添加id屬性
        entity.addIdProperty();
        //添加列userId,指定非空,默認可爲空
        entity.addStringProperty("userId").notNull();
        //添加列username  
        entity.addStringProperty("username");
        //添加列age
        entity.addIntProperty("age");
        //添加列phone
        entity.addStringProperty("phone");
    }

    public static void main(String[] args) throws Exception {
        //第一個參數是數據庫版本號,第二個參數是所在包名
        Schema schema = new Schema(1, "com.usst.chensl.introductdemo.db");
        addDetail(schema);

        try {
            //第二個參數是我們前面新建的空文件夾sec-gen,這裏採用相對路徑的寫法
            //'..'代表工程前一個目錄,接着是工程名/app(AndroidStudio生成)/src-gen(自己建的)
            new DaoGenerator().generateAll(schema, "../IntroducDemo/app/src-gen");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Entity可以看作是一張表,它使用構造器模式來設計,可以指定某一列的各種數據庫屬性,例如非空,自增,升降序,主鍵等。

注意:必須要使用run main()這種方法,在AndroidStudio下直接對該文件右鍵即可選擇run main(),之前LZ試過在onCreate()裏跑結果報錯

下面來看看初始化出來的東西:
項目實例3

  • user實體類,註釋已經說明是GreenDao自動生成的。其實就跟自己建實體類一樣,不過現在是代碼自動生成

    package com.usst.chensl.introductdemo.db;
    
    // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. 
    /**
     * Entity mapped to table USER.
     */
    public class User {
    
        private Long id;
        private String userId;
        private String username;
        private String age;
        private String phone;
    
        public User() {
        }
    
        public User(Long id) {
            this.id = id;
        }
    
        public User(Long id, String userId, String username, String age, String phone) {
            this.id = id;
            this.userId = userId;
            this.username = username;
            this.age = age;
            this.phone = phone;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getUserId() {
            return userId;
        }
    
        public void setUserId(String userId) {
            this.userId = userId;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone;
        }
    
    }
    
  • userDao,如果自己實現過簡單的ORM框架的話,很容易就看出這個是對sql語句的包裝,有createTable()dropTable,readEntity,updateKeyAfterInsert,這些望文生義的方法

    package com.usst.chensl.introductdemo.db;
    
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteStatement;
    
    import de.greenrobot.dao.AbstractDao;
    import de.greenrobot.dao.Property;
    import de.greenrobot.dao.internal.DaoConfig;
    
    import com.usst.chensl.introductdemo.db.User;
    
    // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
    /** 
     * DAO for table USER.
    */
    public class UserDao extends AbstractDao<User, Long> {
    
        public static final String TABLENAME = "USER";
    
        /**
         * Properties of entity User.<br/>
         * Can be used for QueryBuilder and for referencing column names.
        */
        public static class Properties {
            //參數分別是(列數,類型,Java實體類的變量名,是否主鍵,數據庫列名)
            //因爲上面有entity.addIdProperty(),所以自動生成了主鍵'_id'
            public final static Property Id = new Property(0, Long.class, "id", true, "_id");
            public final static Property UserId = new Property(1, String.class, "userId", false, "USER_ID");
            public final static Property Username = new Property(2, String.class, "username", false, "USERNAME");
            public final static Property Age = new Property(3, String.class, "age", false, "AGE");
            public final static Property Phone = new Property(4, String.class, "phone", false, "PHONE");
        };
    
    
        public UserDao(DaoConfig config) {
            super(config);
        }
    
        public UserDao(DaoConfig config, DaoSession daoSession) {
            super(config, daoSession);
        }
    
        /** Creates the underlying database table. */
        public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
            String constraint = ifNotExists? "IF NOT EXISTS ": "";
            db.execSQL("CREATE TABLE " + constraint + "'USER' (" + //
                    "'_id' INTEGER PRIMARY KEY ," + // 0: id
                    "'USER_ID' TEXT," + // 1: userId
                    "'USERNAME' TEXT," + // 2: username
                    "'AGE' TEXT," + // 3: age
                    "'PHONE' TEXT);"); // 4: phone
        }
    
        /** Drops the underlying database table. */
        public static void dropTable(SQLiteDatabase db, boolean ifExists) {
            String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'USER'";
            db.execSQL(sql);
        }
    
        /** @inheritdoc */
        @Override
        protected void bindValues(SQLiteStatement stmt, User entity) {
            stmt.clearBindings();
    
            Long id = entity.getId();
            if (id != null) {
                stmt.bindLong(1, id);
            }
    
            String userId = entity.getUserId();
            if (userId != null) {
                stmt.bindString(2, userId);
            }
    
            String username = entity.getUsername();
            if (username != null) {
                stmt.bindString(3, username);
            }
    
            String age = entity.getAge();
            if (age != null) {
                stmt.bindString(4, age);
            }
    
            String phone = entity.getPhone();
            if (phone != null) {
                stmt.bindString(5, phone);
            }
        }
    
        /** @inheritdoc */
        @Override
        public Long readKey(Cursor cursor, int offset) {
            return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
        }    
    
        /** @inheritdoc */
        @Override
        public User readEntity(Cursor cursor, int offset) {
            User entity = new User( //
                cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
                cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // userId
                cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // username
                cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // age
                cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4) // phone
            );
            return entity;
        }
    
        /** @inheritdoc */
        @Override
        public void readEntity(Cursor cursor, User entity, int offset) {
            entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
            entity.setUserId(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
            entity.setUsername(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
            entity.setAge(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
            entity.setPhone(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
         }
    
        /** @inheritdoc */
        @Override
        protected Long updateKeyAfterInsert(User entity, long rowId) {
            entity.setId(rowId);
            return rowId;
        }
    
        /** @inheritdoc */
        @Override
        public Long getKey(User entity) {
            if(entity != null) {
                return entity.getId();
            } else {
                return null;
            }
        }
    
        /** @inheritdoc */
        @Override    
        protected boolean isEntityUpdateable() {
            return true;
        }
    
    }
    
  • DaoSession,數據庫Session

    package com.usst.chensl.introductdemo.db;
    
    import android.database.sqlite.SQLiteDatabase;
    
    import java.util.Map;
    
    import de.greenrobot.dao.AbstractDao;
    import de.greenrobot.dao.AbstractDaoSession;
    import de.greenrobot.dao.identityscope.IdentityScopeType;
    import de.greenrobot.dao.internal.DaoConfig;
    
    import com.usst.chensl.introductdemo.db.User;
    
    import com.usst.chensl.introductdemo.db.UserDao;
    
    // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
    
    /**
     * {@inheritDoc}
     * 
     * @see de.greenrobot.dao.AbstractDaoSession
     */
    public class DaoSession extends AbstractDaoSession {
    
        private final DaoConfig userDaoConfig;
    
        private final UserDao userDao;
    
        public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
                daoConfigMap) {
            super(db);
    
            userDaoConfig = daoConfigMap.get(UserDao.class).clone();
            userDaoConfig.initIdentityScope(type);
    
            userDao = new UserDao(userDaoConfig, this);
    
            registerDao(User.class, userDao);
        }
    
        public void clear() {
            userDaoConfig.getIdentityScope().clear();
        }
    
        public UserDao getUserDao() {
            return userDao;
        }
    
    }
    
  • DaoMaster,對SQLiteDatabase的封裝,包含了UserDao

    package com.usst.chensl.introductdemo.db;
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;
    import de.greenrobot.dao.AbstractDaoMaster;
    import de.greenrobot.dao.identityscope.IdentityScopeType;
    
    import com.usst.chensl.introductdemo.db.UserDao;
    
    // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
    /** 
     * Master of DAO (schema version 1): knows all DAOs.
    */
    public class DaoMaster extends AbstractDaoMaster {
        public static final int SCHEMA_VERSION = 1;
    
        /** Creates underlying database table using DAOs. */
        public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
            UserDao.createTable(db, ifNotExists);
        }
    
        /** Drops underlying database table using DAOs. */
        public static void dropAllTables(SQLiteDatabase db, boolean ifExists) {
            UserDao.dropTable(db, ifExists);
        }
    
        //抽象類
        public static abstract class OpenHelper extends SQLiteOpenHelper {
    
            public OpenHelper(Context context, String name, CursorFactory factory) {
                super(context, name, factory, SCHEMA_VERSION);
            }
    
            @Override
            public void onCreate(SQLiteDatabase db) {
                Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
                createAllTables(db, false);
            }
        }
    
        //真正實現類
        /** WARNING: Drops all table on Upgrade! Use only during development. */
        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);
            }
        }
    
        public DaoMaster(SQLiteDatabase db) {
            super(db, SCHEMA_VERSION);
            registerDaoClass(UserDao.class);
        }
    
    
        public DaoSession newSession() {
            return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
        }
    
        public DaoSession newSession(IdentityScopeType type) {
            return new DaoSession(db, type, daoConfigMap);
        }
    
    }
    

DbMaster的最終目的是獲取DbSession,通過DbSession對數據庫進行操作。

下一篇說GreenDao具體使用,敬請期待~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章