Android数据库框架 greenDAO:3.2.0的集成

1.配置gradle相关:最外层build.gradle配置

buildscript {
    
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://maven.google.com/' }
        maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
    }
}

2.app中:build.gradle配置

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support:support-v13:28.0.0'
    implementation 'com.android.databinding:library:1.3.1 '
    implementation 'com.android.databinding:adapters:1.3.1'
    //很不错的运行时权限管理
    implementation 'com.yanzhenjie:permission:2.0.0-rc12'
    //很不错的开源日志库
    implementation 'com.orhanobut:logger:2.2.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'org.greenrobot:greendao:3.2.0'
    //compile 'net.zetetic:android-database-sqlcipher:3.5.4' //数据库加密时添加
    //compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v1.2.0' //使用数据库升级辅助GreenDaoUpgradleHepler时添加
    compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v2.1.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
}

2.2注意配置 这个,没有配置你的数据库升级GreenDaoUpgradeHelper这个会有问题

allprojects {
    repositories {
        mavenCentral()
        maven {
            url 'https://maven.google.com'
            maven { url "https://jitpack.io" }//配置数据库增加的
            maven { url 'https://maven.fabric.io/public' }
            maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
        }
    }

2.3数据库版本以及Dao的相关设置 

//数据库版本以及Dao的相关设置
greendao {
    //数据库schema版本
    schemaVersion 1
    //设置DaoMaster DaoSession Dao包名,默认的是bean所在的包名
    daoPackage 'com.zw.weimusic.database.dao'
    //设置DaoMaster DaoSeeeion Dao目录,默认是build/generated/source/greendao
    targetGenDir 'src/main/java'
    //设置true,自动生成测试单元
    //generateTests 'true'
    //设置生成的单元测试目录,默认是src/androidTest/java
    //targetGenDirTests 'src/androidTest/java'
}

3.对GreenDao的封装: 

3.1提取AbstractDao常用方法

public class BaseBeanManager {
    private AbstractDao mDao;

    public BaseBeanManager(AbstractDao dao) {
        mDao = dao;
    }

    public void save(T item) {
        mDao.insert(item);
    }

    public void save(T... items) {
        mDao.insertInTx(items);
    }

    public void save(List items) {
        mDao.insertInTx(items);
    }

    public void saveOrUpdate(T item) {
        mDao.insertOrReplace(item);
    }

    public void saveOrUpdate(T... items) {
        mDao.insertOrReplaceInTx(items);
    }

    public void saveOrUpdate(List items) {
        mDao.insertOrReplaceInTx(items);
    }

    public void deleteByKey(K key) {
        mDao.deleteByKey(key);
    }

    public void delete(T item) {
        mDao.delete(item);
    }

    public void delete(T... items) {
        mDao.deleteInTx(items);
    }

    public void delete(List items) {
        mDao.deleteInTx(items);
    }

    public void deleteAll() {
        mDao.deleteAll();
    }

    public void update(T item) {
        mDao.update(item);
    }

    public void update(T... items) {
        mDao.updateInTx(items);
    }

    public void update(List items) {
        mDao.updateInTx(items);
    }

    public T query(K key) {
        return mDao.load(key);
    }

    public List queryAll() {
        return mDao.loadAll();
    }

    public List query(String where, String... params) {
        return mDao.queryRaw(where, params);
    }

    public QueryBuilder queryBuilder() {
        return mDao.queryBuilder();
    }

    public long count() {
        return mDao.count();
    }

    public void refresh(T item) {
        mDao.refresh(item);
    }

    public void detach(T item) {
        mDao.detach(item);
    }
}

3.2 PlayerManager

public class PlayerManager extends BaseBeanManager {

    public PlayerManager(AbstractDao dao) {
        super(dao);
    }

    /**
     * 按照播放的时间降序排列
     *
     * @return
     */
    public List queryAndSort() {
        Query query = queryBuilder().orderDesc(MediaBeanDao.Properties.HistroyTime).build();
        List list = query.list();
        return list;
    }

3.3 管理数据库(打开或关闭、升级、存储位置)

public class DaoManager {
    /**
     * 数据库名称
     */
    private static final String DB_NAME = "DtDatabase.db";
    private static DaoManager mDaoManager;
    private MySQLiteOpenHelper mHelper;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private Context mContext;
    /**
     * 数据库加密,默认不加密
     */
    private boolean encrypt = false;
    private String password = null;

    public DaoManager(Context context) {
        this.mContext = context;
    }

    /**
     * 使用单例模式获得操作数据库的对象
     */
    public static DaoManager getInstance(Context context) {
        if (mDaoManager == null) {
            synchronized (DaoManager.class) {
                if (mDaoManager == null) {
                    mDaoManager = new DaoManager(context);
                }
            }
        }
        return mDaoManager;
    }

    /**
     * 获取DaoSession
     */
    public synchronized DaoSession getDaoSession() {
        if (null == mDaoSession) {
            mDaoSession = getDaoMaster().newSession();
        }
        return mDaoSession;
    }

    /**
     * 将标志位设为true
     */
    public void encryptDatabase(String password) {
        this.encrypt = true;
        this.password = password;
    }

    /**
     * 关闭数据库
     */
    public synchronized void closeDataBase() {
        closeHelper();
        closeDaoSession();
    }

    /**
     * 判断数据库是否存在,如果不存在则创建
     */
    private DaoMaster getDaoMaster() {
        if (null == mDaoMaster) {
            mHelper = new MySQLiteOpenHelper(mContext, DB_NAME, null);
            if (encrypt) {
                mDaoMaster = new DaoMaster(mHelper.getEncryptedWritableDb(password));
            } else {
                mDaoMaster = new DaoMaster(mHelper.getWritableDb());
            }
        }
        return mDaoMaster;
    }

    private void closeDaoSession() {
        if (null != mDaoSession) {
            mDaoSession.clear();
            mDaoSession = null;
        }
    }

    private void closeHelper() {
        if (mHelper != null) {
            mHelper.close();
            mHelper = null;
        }
    }

    /**
     * 数据库升级帮助类,新添加的bean类需要将其Dao类添加在MediaBeanDao.class之后
     */
    public static class MySQLiteOpenHelper extends DaoMaster.OpenHelper {
        public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
            super(context, name, factory);
        }

        @Override
        public void onUpgrade(Database db, int oldVersion, int newVersion) {
            MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {

                @Override
                public void onCreateAllTables(Database db, boolean ifNotExists) {
                    DaoMaster.createAllTables(db, ifNotExists);
                }

                @Override
                public void onDropAllTables(Database db, boolean ifExists) {
                    DaoMaster.dropAllTables(db, ifExists);
                }
            }, MediaBeanDao.class, SearchBeanDao.class);
        }
    }
}

4.GreenDao的使用

@Entity
public class SearchBean {
    @Id(autoincrement = true)
    private Long Id;
    private String name;

    @Generated(hash = 562045751)
    public SearchBean() {
    }
    @Generated(hash = 800185727)
    public SearchBean(Long Id, String name) {
        this.Id = Id;
        this.name = name;
    }
    public Long getId() {
        return Id;
    }

    public void setId(Long id) {
        Id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class DBManagerHelper {

    private static final String TAG = "DBManagerHelper";

    /**
     * 单例模式
     */
    private static DBManagerHelper instance = null;

    public static DBManagerHelper getInstance() {
        if (instance == null) {
            synchronized (DBManagerHelper.class) {
                if (instance == null) {
                    instance = new DBManagerHelper();
                }
            }
        }
        return instance;
    }

    /**
     * 查询数据库所有的数据
     */
    public List queryAllData() {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        List mediaBeanList = playerManager.queryAndSort();
        return mediaBeanList;
    }


    /**
     * 根据id查询数据库中的单个数据
     */
    public MediaBean queryOneData(String id) {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        MediaBean mediaBean = playerManager.query(id);
        return mediaBean;
    }

    /**
     * 根据数据库所有的数据的总条目
     */
    public Integer queryAllCount() {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        int size = playerManager.queryAll().size();
        return size;
    }


    /**
     * 保存单个历史记录到本地
     */
    public void saveHistroyData(MediaBean mediaBean) {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        playerManager.saveOrUpdate(mediaBean);
    }

    /**
     * 查询最新的单个历史
     */
    public MediaBean queryOneHistroyData() {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        List mList = playerManager.queryAndSort();
        return mList.get(0);
    }

    /**
     * 删除多个历史记录
     */
    public void deleteHistroyData(List list) {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        playerManager.delete(list);
    }

    /**
     * 删除单个历史记录
     */
    public void deleteHistroyData(MediaBean bean) {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        playerManager.delete(bean);
    }

    /**
     * 同步数据到服务端
     */
    public void submitHistroyDataService() {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        List mList = playerManager.queryAll();
    }

    /**
     * 同步数据到本地数据库:
     */
    public void synchronizationHistroyToDB(List list) {
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        playerManager.saveOrUpdate(list);//插入数据库
        //限制20条
        countLimit(20);
    }

    /**
     * 数据库限制条数据
     *
     * @return
     */
    private List countLimit(int count) {
        List beanList = new ArrayList<>();
        List deleteList=new ArrayList<>();
        PlayerManager playerManager = ManagerFactory.getInstance().getPlayerManager();
        List mList = playerManager.queryAndSort();
        if (mList.size() <= count) {
            beanList.addAll(mList);
        } else {
            //需要的100条数据
            beanList.addAll(mList.subList(0, count)) ;
            //删除的数据
            deleteList.addAll(mList.subList(count, mList.size()));
            deleteHistroyData(deleteList);
        }
        return beanList;
    }
}

5.参考文献

https://www.jianshu.com/p/cc7c1ecdfacf

你可能感兴趣的:(android数据库)