美文网首页android数据库
Android 数据库框架 GreenDao的使用

Android 数据库框架 GreenDao的使用

作者: __素颜__ | 来源:发表于2018-04-08 17:49 被阅读1172次

    前言

    年前做了一个访问通讯录的需求,需要将用户的通讯录存入本地数据库中,以前用过原生的SQLite数据库,但是需要自己封装,自己写sql语句,所以这次需求找了一个数据库框架使用GreenDao,仔细找了一下发现 Android 平台上的数据库框架可真够多,但是有一个共同特点就是基于对象关系映射模型的。实现的目标也都是不需要写 SQL 语句,通过对对象的操作保存和操作数据。要是从语法的简洁性来说都有自己的特点,总的来说不相上下。

    下面来说一下GreenDao数据库的优势

    1.存取速度快;

    2.支持数据库加密;

    3.轻量级;

    4.激活实体;

    5.支持缓存;

    6.代码自动生成;

    总结:效率很高,插入和更新的速度是sqlite的2倍,加载实体的速度是ormlite(也是一个数据库框架)的4.5倍,目前git上一直在做更新维护,start数量为9000多。

    下面我们言简意赅,主要说下GreenDao数据库的使用。

    一、GreenDao数据库的使用

    第一步: 在项目的.gradle文件里面添加

    buildscript {
       repositories {
       jcenter()
       mavenCentral()
     }
     dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
    
     }
    }  
    

    第二步:在moddle的.gradle文件里面添加

    
    android {
    greendao {
       schemaVersion 1
       daoPackage 'com.jyjt.ydyl.greendao.gen'
       targetGenDir 'src/main/java'  
    }
    }  
    

    依赖里面添加

    compile 'org.greenrobot:greendao:3.1.0'
    compile 'org.greenrobot:greendao-generator:3.1.0'
    
    

    第三步: 添加Bean类,用User举例子 , 一定要记得注解@Entity 如:

    @Entity 
    public class PhoneContactsEntity {
     @Id(autoincrement = true)
     private Long id;
     //姓名  
    public String name = "";
     //电话 
     public String phone = "";
     //联系人id  
    public String contactsId = "";
     //电话和姓名 
     public String phoneName = "";
    
    }
    

    第四步:编译项目,PhoneContactsEntity实体类会自动编译,生成get、set方法并且会在com.jyjt.ydyl.greendao.gen目录下生成三个文件;

    image.png

    第五步:Application中进行初始化,创建表;

    import android.app.Application;
    import android.database.sqlite.SQLiteDatabase;
    import com.example.john.greendaodemo.gen.DaoMaster;
    import com.jyjt.ydyl.greendao.gen.DaoSession;
    
    public class AppApplication extends Application {
    
    private DaoMaster.DevOpenHelper mHelper;
       private SQLiteDatabase db;
       private DaoMaster mDaoMaster;
       private DaoSession mDaoSession;
    public static AppApplication instances;
    
       @Override
    public void onCreate() {
           super.onCreate();
           instances = this;
           setDatabase();
       }
    
       /**
    * 单例模式 * *
    */ 
    public static AppApplication getInstances() {
           return instances;
     }
    
    
     /* 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
    可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。*/
    
    private void setDatabase() {
      mHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
      db = mHelper.getWritableDatabase();  mDaoMaster = new DaoMaster(db);
      mDaoSession = mDaoMaster.newSession();
     }
    
      public DaoSession getDaoSession() {
           return mDaoSession;
      }
    
      public SQLiteDatabase getDb() {
           return db;
      }
    }
    
    

    第六步:对表的具体操作;

    public class SQLiteUtils {
       private static SQLiteUtils instance;
       PhoneContactsEntityDao phoneContactsEntityDao;
       DaoSession daoSession;
    
       private SQLiteUtils() {
           phoneContactsEntityDao = MyApplication.getmApplication().getDaoSession().getPhoneContactsEntityDao();
           daoSession = MyApplication.getmApplication().getDaoSession();
       }
    
       public static SQLiteUtils getInstance() {
           if (instance == null) {
               synchronized (SQLiteUtils.class) {
                   if (instance == null) {
                       instance = new SQLiteUtils();
                   }
               }
           }
           return instance;
       }
    
       //增加  
    public void addContacts(PhoneContactsEntity testBean) {
           phoneContactsEntityDao.insert(testBean);
       }
    
       //删除 
    public void deleteContacts(PhoneContactsEntity testBean) {
           phoneContactsEntityDao.delete(testBean);
       }
    
       //修改  
    public void updateContacts(PhoneContactsEntity testBean) {
           phoneContactsEntityDao.update(testBean);
       }
    
       //条件查询
     public List selectAllContacts() {
       phoneContactsEntityDao.detachAll();//清除缓存 
       List list1 = phoneContactsEntityDao.queryBuilder().where(PhoneContactsEntityDao.Properties.LogingId.eq(ConfigUtils.getUid())).build().li  st();
       return list1 == null ? new ArrayList() : list1;
    }
    
       //删除表中内容  
    public void deleteAllContact() {
          phoneContactsEntityDao.deleteAll();
    }
    

    二、where 和whereOr的使用

    whereOr :或条件查询 多个或用“,”分隔

    where:和条件查询 多个和用“,”分隔

    例如:当前用户,展示状态 查询用户手机号码或姓名中包含有关键字的人

    List list = phoneContactsEntityDao.queryBuilder().whereOr(PhoneContactsEntityDao.Properties.Phone.like("%" + key + "%"),PhoneContactsEntityDao.Properties.Name.like("%" + key + "%")).where(PhoneContactsEntityDao.Properties.IsShow.eq("1"), PhoneContactsEntityDao.Properties.LogingId.eq(ConfigUtils.getUid())).build().list();
    

    三.GreeDao使用sql语句

    当然有可能需求复杂的时候GreenDao提供的api实现不了你的需求,但是GreeDao支持使用sql语句,下面是通讯录项目中用到的sql语句

    String sql = "update `" + talbelName + "` set `USER_SATE` = '1' where `LOGING_ID` = '" + ConfigUtils.getUid() + "' and PHONE='" + upSateContacts.get(i).getPhone() + "'";
    
    String sql = "delete from `" + talbelName + "` where `LOGING_ID` = '" + ConfigUtils.getUid() + "'";
    
    String sql = "update `" + talbelName + "` set `IS_SHOW` = '0' where `LOGING_ID` = '" + ConfigUtils.getUid() + "' and PHONE IN (" + phone + ")";
    
    daoSession.getDatabase().execSQL(sql);
    

    四、sql语句

    下面让我们来具体温习下SQL语句

    1、查询数据

     select * from table1 where 范围;
    

    2、插入数据

    insert into table1(field1,field2) values(value1,value2);
    

    3、删除数据

    delete from table1 where 范围;
    

    4、更新数据

    update table1 set field1=value1, field2=value2 where 范围;
    

    5、模糊查询

     select * from table1 where field1 like ’%value1%’;
    

    6、排序

     select * from table1 order by field1,field2 [desc];
    

    7、分页查询(limit 要放到最后)

     select * from table1 where 范围 limit 0,10;
    

    8、求总数

     select count as totalcount from table1;
    

    9、求和

    select sum(field1) as sumvalue from table1;
    

    10、求平均数

     select avg(field1) as avgvalue from table1;
    

    11、求最大

     select max(field1) as maxvalue from table;
    

    12、求最小

     select min(field1) as minvalue from table1; 
    

    相关文章

      网友评论

      本文标题:Android 数据库框架 GreenDao的使用

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