Android greendao的使用

2020-01-19  本文已影响0人  MorningandSun

1.项目下的build.gradle中的allprojects下添加

         mavenCentral()

2.dependencies 中添加

     classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

3.app下的build.gradle中添加

//数据库
    implementation 'org.greenrobot:greendao:3.2.2'


  dataBinding {
        enabled = true
    }
    greendao {
        schemaVersion 1 //当前数据库版本
    }

4.创建数据库Model

  @Entity
public class Dao_Message {
    @Id(autoincrement = true)
    private Long _id;
    private String title;
    private String content;
    private int tran_id;
    private int tran_type; //0发送 1接受
    private Long time;
    private int read; //0未读 1 已读

//下面的是build之后自动生成的
    @Generated(hash = 1069108103)
    public Dao_Message(Long _id, String title, String content, int tran_id,
            int tran_type, Long time, int read) {
        this._id = _id;
        this.title = title;
        this.content = content;
        this.tran_id = tran_id;
        this.tran_type = tran_type;
        this.time = time;
        this.read = read;
    }
    @Generated(hash = 1687853729)
    public Dao_Message() {
    }
    public Long get_id() {
        return this._id;
    }
    public void set_id(Long _id) {
        this._id = _id;
    }
    public String getTitle() {
        return this.title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return this.content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public int getTran_id() {
        return this.tran_id;
    }
    public void setTran_id(int tran_id) {
        this.tran_id = tran_id;
    }
    public int getTran_type() {
        return this.tran_type;
    }
    public void setTran_type(int tran_type) {
        this.tran_type = tran_type;
    }
    public Long getTime() {
        return this.time;
    }
    public void setTime(Long time) {
        this.time = time;
    }
    public int getRead() {
        return this.read;
    }
    public void setRead(int read) {
        this.read = read;
    }
   
}

5.使用 创建DaoManager

public class DaoManager {
    private static final String TAG = DaoManager.class.getSimpleName();
    private static final String DB_NAME = "xn_message";

    private Context context;

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

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

    private DaoManager()
    {
        setDebug();
    }

    public void init(Context context)
    {
        this.context = context;
    }

    /**
     * 判断是否有存在数据库,如果没有则创建
     *
     * @return
     */
    public DaoMaster getDaoMaster()
    {
        if (sDaoMaster == null)
        {
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
            sDaoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return sDaoMaster;
    }

    /**
     * 完成对数据库的添加、删除、修改、查询操作,仅仅是一个接口
     *
     * @return
     */
    public DaoSession getDaoSession()
    {
        if (sDaoSession == null)
        {
            if (sDaoMaster == null)
            {
                sDaoMaster = getDaoMaster();
            }
            sDaoSession = sDaoMaster.newSession();
        }
        return sDaoSession;
    }

    /**
     * 打开输出日志,默认关闭
     */
    public void setDebug()
    {
        if (BuildConfig.DEBUG)
        {
            QueryBuilder.LOG_SQL = true;
            QueryBuilder.LOG_VALUES = true;
        }
    }

    /**
     * 关闭所有的操作,数据库开启后,使用完毕要关闭
     */
    public void closeConnection()
    {
        closeHelper();
        closeDaoSession();
    }

    public void closeHelper()
    {
        if (sHelper != null)
        {
            sHelper.close();
            sHelper = null;
        }
    }

    public void closeDaoSession()
    {
        if (sDaoSession != null)
        {
            sDaoSession.clear();
            sDaoSession = null;
        }
    }
}

DaoUtils.java

public class DaoUtils {
    private static final String TAG = DaoUtils.class.getSimpleName();
    private DaoManager mManager;

    public DaoUtils(Context context){
        mManager = DaoManager.getInstance();
        mManager.init(context);
    }

    /**
     * 完成meizi记录的插入,如果表未创建
     * @return
     */
    public boolean insertMessage(Dao_Message dao_message){
        boolean flag = false;
        flag = mManager.getDaoSession().getDao_MessageDao().insert(dao_message) == -1 ? false : true;
        Log.i(TAG, "insert Meizi :" + flag + "-->" + dao_message.toString());
        return flag;
    }

    /**
     * 插入多条数据,在子线程操作
     * @return
     */
    public boolean insertMultMessage(final List<Dao_Message> dao_messageList) {
        boolean flag = false;
        try {
            mManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (Dao_Message dao_message : dao_messageList) {
                        mManager.getDaoSession().insertOrReplace(dao_message);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改一条数据
     * @return
     */
    public boolean updateMessage(Dao_Message dao_message){
        boolean flag = false;
        try {
            mManager.getDaoSession().update(dao_message);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除单条记录
     * @return
     */
    public boolean deleteMessage(Dao_Message dao_message){
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().delete(dao_message);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除所有记录
     * @return
     */
    public boolean deleteAll(){
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().deleteAll(Dao_Message.class);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 查询所有记录
     * @return
     */
    public List<Dao_Message> queryAllMessage(){
        return mManager.getDaoSession().loadAll(Dao_Message.class);
    }

    /**
     * 根据主键id查询记录
     * @param key
     * @return
     */
    public Dao_Message queryMessageById(long key){
        return mManager.getDaoSession().load(Dao_Message.class, key);
    }

    /**
     * 使用native sql进行查询操作
     */
    public List<Dao_Message> queryMessageByNativeSql(String sql, String[] conditions){
        return mManager.getDaoSession().queryRaw(Dao_Message.class, sql, conditions);
    }

    /**
     * 使用queryBuilder进行查询
     * @return
     */
    public List<Dao_Message> queryMessageByQueryBuilder(long id){
        QueryBuilder<Dao_Message> queryBuilder = mManager.getDaoSession().queryBuilder(Dao_Message.class);
        return queryBuilder.where(Dao_MessageDao.Properties._id.eq(id)).list();
    }

    /**
     * 使用queryBuilder进行查询
     * @return
     */
    public List<Dao_Message> queryMessageByRead(){
        QueryBuilder<Dao_Message> queryBuilder = mManager.getDaoSession().queryBuilder(Dao_Message.class);
        return queryBuilder.where(Dao_MessageDao.Properties.Read.eq(0)).list();
    }
}

6.在MyApplication 的OnCreat()中添加

initGreenDao();

 private void initGreenDao()
    {
        DaoManager mManager = DaoManager.getInstance();
        mManager.init(this);
    }

7.调用

 Dao_Message dao_message=new Dao_Message();
  new DaoUtils(context).insertMessage(dao_message);
上一篇 下一篇

猜你喜欢

热点阅读