美文网首页Androidandroid
GreenDao(1)--项目配置

GreenDao(1)--项目配置

作者: 豆沙包67 | 来源:发表于2015-08-17 11:16 被阅读5515次

    项目配置

    • grdle配置
      在Android Studio的build.gradle配上
      compile 'de.greenrobot:greendao:1.3.7'
      compile 'de.greenrobot:greendao-generator:1.3.1'

    • 生成代码

    项目示例2

    我们需要在包根目录新建一个Java文件,做初始化工作。
    如图所示,包的根目录是'com.usst.chensl.greendaodemo',创建一个名为'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 {
            //生成数据库文件的目标包名//target package for dao files
            //第一个参数是数据库版本号,第二个参数是包的根目录的包
            Schema schema = new Schema(1, "db");
            addDetail(schema);
            try {
                //第二个参数是src-gen文件夹相对路径
                //'..'代表工程前一个目录,接着是工程名/app(AndroidStudio生成)/
                new DaoGenerator().generateAll(schema, "../GreenDaoDemo/app/src/main/java/com/usst/chensl/greendaodemo/");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Entity可以看作是一张表,它使用构造器模式来设计,可以指定某一列的各种数据库属性,例如非空,自增,升降序,主键等。

    同时,在工程目录下新建src-gen文件夹,放置代码生成的数据库文件。

    项目文件结构目录

    对着ExampleDaoGenerator右键,选择run ... main(),会在src-gen文件夹中生成四个文件。

    注意:必须要使用run main()这种方法,在AndroidStudio下直接对该文件右键即可选择run main(),之前LZ试过在onCreate()里跑结果报错

    下面来看看初始化出来的东西:

    项目实例3

    db包拖动到包的根目录下,然后可以将src-gen文件夹下的东西全部删掉了。

    初始化完成

    初始化完成后,'ExampleDaoGenerator'就没用了,留着修改后可以创建另一个表,不需要可以删除。

    • 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具体使用,敬请期待~

    相关文章

      网友评论

      本文标题:GreenDao(1)--项目配置

      本文链接:https://www.haomeiwen.com/subject/oekwqttx.html