第三方开源库--> GreenDao 数据库

Posted Kevin_小飞象

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第三方开源库--> GreenDao 数据库相关的知识,希望对你有一定的参考价值。

简介

目前最新版本是 3.3.0。
GitHub:greenDAO

特点

  • 最佳性能 (可能是 android 中最快的 ORM) ,基准测试也是开源的;
  • 易于使用的功能强大的 api,涵盖关系和连接;
  • 最小的内存消耗;
  • 小型库大小(< 100KB) ,以保持较低的构建时间,并避免65k 方法限制;
  • 数据库加密:greenDAO 支持 SQLCipher 来保证用户数据的安全;
  • 强大而活跃的社区交流支持。

基本配置

  1. 在项目目录下 build.gradle 添加依赖:
    buildscript 
    repositories 
        google()
        mavenCentral()
    
    dependencies 
        classpath "com.android.tools.build:gradle:4.2.1"
        classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0'
    

  1. 在 app目录下 build.gradle 添加依赖:
plugins 
    id 'com.android.application'
    id 'org.greenrobot.greendao'

--------------------------------------
    // greendao
    implementation 'org.greenrobot:greendao:3.3.0'

    // RecyclerAdapter
    implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.30'

----------------------------------------------
greendao 
    schemaVersion 1 //当前数据库版本

核心类

1. DaoMaster.java

/**
 * Created on 2021/7/14 13:56
 *
 * @author Gong Youqiang
 */
public class DaoMaster extends AbstractDaoMaster 
    public static final int SCHEMA_VERSION = 1;

    /** Creates underlying database table using DAOs. */
    public static void createAllTables(Database db, boolean ifNotExists) 
        UserDao.createTable(db, ifNotExists);
    

    /** Drops underlying database table using DAOs. */
    public static void dropAllTables(Database db, boolean ifExists) 
        UserDao.dropTable(db, ifExists);
    

    /**
     * WARNING: Drops all table on Upgrade! Use only during development.
     * Convenience method using a @link DevOpenHelper.
     */
    public static DaoSession newDevSession(Context context, String name) 
        Database db = new DevOpenHelper(context, name).getWritableDb();
        DaoMaster daoMaster = new DaoMaster(db);
        return daoMaster.newSession();
    

    public DaoMaster(SQLiteDatabase db) 
        this(new StandardDatabase(db));
    

    public DaoMaster(Database 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);
    

    /**
     * Calls @link #createAllTables(Database, boolean) in @link #onCreate(Database) -
     */
    public static abstract class OpenHelper extends DatabaseOpenHelper 
        public OpenHelper(Context context, String name) 
            super(context, name, SCHEMA_VERSION);
        

        public OpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) 
            super(context, name, factory, SCHEMA_VERSION);
        

        @Override
        public void onCreate(Database 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) 
            super(context, name);
        

        public DevOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) 
            super(context, name, factory);
        

        @Override
        public void onUpgrade(Database 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. DaoSession.java
/**
 * Created on 2021/7/14 13:58
 *
 * @author Gong Youqiang
 */
public class DaoSession extends AbstractDaoSession 
    private final DaoConfig userDaoConfig;

    private final UserDao userDao;

    public DaoSession(Database 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.clearIdentityScope();
    

    public UserDao getUserDao() 
        return userDao;
    

  1. UserDao.java
/**
 * Created on 2021/7/14 13:58
 *
 * @author Gong Youqiang
 */
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 
        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, "USER_NAME");
        public final static Property Age = new Property(3, int.class, "age", false, "AGE");
    


    public UserDao(DaoConfig config) 
        super(config);
    

    public UserDao(DaoConfig config, DaoSession daoSession) 
        super(config, daoSession);
    

    /** Creates the underlying database table. */
    public static void createTable(Database db, boolean ifNotExists) 
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "\\"USER\\" (" + //
                "\\"_id\\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
                "\\"USER_ID\\" TEXT UNIQUE ," + // 1: userId
                "\\"USER_NAME\\" TEXT," + // 2: userName
                "\\"AGE\\" INTEGER NOT NULL );"); // 3: age
    

    /** Drops the underlying database table. */
    public static void dropTable(Database db, boolean ifExists) 
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\\"USER\\"";
        db.execSQL(sql);
    

    @Override
    protected final void bindValues(DatabaseStatement 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);
        
        stmt.bindLong(4, entity.getAge());
    

    @Override
    protected final 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);
        
        stmt.bindLong(4, entity.getAge());
    

    @Override
    public Long readKey(Cursor cursor, int offset) 
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    

    @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.getInt(offset + 3) // age
        );
        return entity;
    

    @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.getInt(offset + 3));
    

    @Override
    protected final Long updateKeyAfterInsert(User entity, long rowId) 
        entity.setId(rowId);
        return rowId;
    

    @Override
    public Long getKey(User entity) 
        if(entity != null) 
            return entity.getId();
         else 
            return null;
        
    

    @Override
    public boolean hasKey(User entity) 
        return entity.getId() != null;
    

    @Override
    protected final boolean isEntityUpdateable() 
        return true;
    

  1. 实体类
/**
 * Created on 2021/7/14 13:53
 *
 * @author Gong Youqiang
 */
@Entity
public class User 
    @Id(autoincrement = true)
    private Long id;

    @Unique
    private String userId;

    @Property
    private String userName;

    @Property
    private int age;

    @Generated(hash = 1975221261)
    public User(Long id, String userId, String userName, int age) 
        this.id = id;
        this.userId = userId;
        this.userName = userName;
        this.age = age;
    

    @Generated(hash = 586692638)
    public User() 
    

    public Long getId() 
        return this.id;
    

    public void setId(Long id) 
        this.id = id;
    

    public String getUserId() 
        return this.userId;
    

    public void setUserId(String userId) 
        this.userId = userId;
    

    public String getUserName() 
        return this.userName;
    

    public void setUserName(String userName) 
        this.userName = userName;
    

    public int getAge() 
        return this.age;
    

    public void setAge(int age) 
        this.age = age;
    

Demo

效果图

代码

  1. DaoManager.java
/**
 * Created on 2021/7/14 13:55
 *  创建数据库、创建数据库表、包含增删改查的操作
 * @author Gong Youqiang
 */
public class DaoManager 
    private static final String TAG = DaoManager.class.getSimpleName();
    private static final String DB_NAME = "RECORD_DB";

    private Application mApplication;

    //多线程中要被共享的使用volatile关键字修饰
    private volatile static DaoManager manager = new DaoManager();
    private DaoMaster mDaoMaster;
    private DaoMaster.DevOpenHelper mHelper;
    private DaoSession mDaoSession;

    /**
     * 单例模式获得操作数据库对象
     */
    public static DaoManager getInstance() 
        return manager;
    

    private DaoManager() 
        setDebug();
    

    public void init(Application application) 
        this.mApplication = application;
    

    /**
     * 判断是否有存在数据库,如果没有则创建
     */
    public DaoMaster getDaoMaster() 
        if 李洪强详细介绍SDWebImage

Android GreenDao清空数据库的方法

开源框架GreenDao的操作

android room详解

第三方开源库-->RecyclerView 侧滑菜单(侧滑删除) 开源库整理

Android greenDAO数据库配置教程