GreenDao使用总结

在Android开发过程中,有时候我们需要使用SQLite数据库去本地存储一些临时文件,之前,我们的做法是通过SQLiteOpenHelper实现创建数据库,以及迭代开发中的数据库数据 内容 字段 变更时处理。

优点

1.通常我们在使用GreenDao的时候,我们只需定义数据模型,GreenDao框架将创建数据对象(实体)和DAO(数据访问对象),能够节省部分代码。
2.不向性能妥协,使用了GreenDao,大多数实体可以以每秒几千个实体的速率进行插入,更新和加载。
3.GreenDao支持加密数据库来保护敏感数据。
4.微小的依赖库,GreenDao的关键依赖库大小不超过100kb.
5.如果需要,实体是可以被激活的。而活动实体可以透明的解析关系(我们要做的只是调用getter即可),并且有更新、删除和刷新方法,以便访问持久性功能。
6.GreenDao允许您将协议缓冲区(protobuf)对象直接保存到数据库中。如果您通过protobuf通话到您的服务器,则不需要另一个映射。常规实体的所有持久性操作都可以用于protobuf对象。所以,相信这是GreenDao的独特之处。
7.自动生成代码,我们无需关注实体类以及Dao,因为GreenDao已经帮我们生成了。
8.开源 有兴趣的同学可以查看源码,深入去了解机制。

GreenDao对外提供的核心类简介

1.DaoMaster

DaoMaster保存数据库对象(SQLiteDatabase)并管理特定模式的Dao类。它具有静态方法来创建表或将他们删除。其内部类OpenHelper和DevOpenHelper是在SQLite数据库中创建模式的SQLiteOpenHelper实现。

2.DaoSession

管理特定模式的所有可用Dao对象,您可以使用其中一个getter方法获取。DaoSession还为实体提供了一些通用的持久性方法,如插入,加载,更新,刷新和删除。最后,DaoSession对象也跟踪一个身份范围。

3.Dao层

数据访问对象(Dao)持续存在并查询实体。对于每个实体,GreenDao生成一个Dao,它比DaoSession有更多的持久化方法,例如:count,loadAll和insertInTx。

4.实体

持久对象,通常实体是使用标准Java属性(如POJO或JavaBean)来表示数据库的对象。

GreenDao使用

1.在工程目录下build.gradle下添加插件

buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath <span class="hljs-string">'com.android.tools.build:gradle:3.1.2'</span>
    classpath <span class="hljs-string">'org.greenrobot:greendao-gradle-plugin:3.2.2'</span> <span class="hljs-comment">// 添加插件 更好支持GreenDao</span>

    <span class="hljs-comment">// <span class="hljs-doctag">NOTE:</span> Do not place your application dependencies here; they belong</span>
    <span class="hljs-comment">// in the individual module build.gradle files</span>
}

}

然后Sync Now即可。

2.在项目目录下的build.gradle下添加插件依赖

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'

接下来继续添加依赖库

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'org.greenrobot:greendao:3.2.2' // 添加库
}

再接下来就是初始化GreenDao配置。

greendao {
        schemaVersion 1 //当前数据库版本
    }

然后Sync Now即可。
到这里为止,GreenDao的基本配置就大差不差了。

使用Demo

1.定义一个实体类

  @Id(autoincrement = true)//设置自增长
    private Long id;
<span class="hljs-meta">@Index</span>(unique = <span class="hljs-keyword">true</span>)<span class="hljs-comment">//设置唯一性</span>
<span class="hljs-keyword">private</span> String perNo;<span class="hljs-comment">//人员编号</span>

<span class="hljs-keyword">private</span> String name;<span class="hljs-comment">//人员姓名</span>

<span class="hljs-keyword">private</span> String sex;<span class="hljs-comment">//人员姓名</span>

在我们Make Project后,实体内的变化如下所示:

@Entity
public class PersonInfor {
    @Id(autoincrement = true)//设置自增长
    private Long id;
<span class="hljs-meta">@Index</span>(unique = <span class="hljs-keyword">true</span>)<span class="hljs-comment">//设置唯一性</span>
<span class="hljs-keyword">private</span> String perNo;<span class="hljs-comment">//人员编号</span>

<span class="hljs-keyword">private</span> String name;<span class="hljs-comment">//人员姓名</span>

<span class="hljs-keyword">private</span> String sex;<span class="hljs-comment">//人员姓名</span>

<span class="hljs-meta">@Generated</span>(hash = <span class="hljs-number">1311768890</span>)
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PersonInfor</span><span class="hljs-params">(Long id, String perNo, String name, String sex)</span> </span>{
    <span class="hljs-keyword">this</span>.id = id;
    <span class="hljs-keyword">this</span>.perNo = perNo;
    <span class="hljs-keyword">this</span>.name = name;
    <span class="hljs-keyword">this</span>.sex = sex;
}

<span class="hljs-meta">@Generated</span>(hash = <span class="hljs-number">1362534400</span>)
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PersonInfor</span><span class="hljs-params">()</span> </span>{
}

<span class="hljs-function"><span class="hljs-keyword">public</span> Long <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.id;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(Long id)</span> </span>{
    <span class="hljs-keyword">this</span>.id = id;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPerNo</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.perNo;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPerNo</span><span class="hljs-params">(String perNo)</span> </span>{
    <span class="hljs-keyword">this</span>.perNo = perNo;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.name;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
    <span class="hljs-keyword">this</span>.name = name;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getSex</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.sex;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setSex</span><span class="hljs-params">(String sex)</span> </span>{
    <span class="hljs-keyword">this</span>.sex = sex;
}

}

我们可以看到编译后1.自动生成无参,有参构造。2.自动生成getter,setter方法。

2.封装数据库操作类

因为我们对数据库的操作无非就是增删改查四个操作,所以我们将他们简单封装一下。

public class DbController {
    /**
     * Helper
     */
    private DaoMaster.DevOpenHelper mHelper;//获取Helper对象
    /**
     * 数据库
     */
    private SQLiteDatabase db;
    /**
     * DaoMaster
     */
    private DaoMaster mDaoMaster;
    /**
     * DaoSession
     */
    private DaoSession mDaoSession;
    /**
     * 上下文
     */
    private Context context;
    /**
     * dao
     */
    private PersonInforDao personInforDao;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> DbController mDbController;

<span class="hljs-comment">/**
 * 获取单例
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> DbController getInstance(Context context){
    <span class="hljs-keyword">if</span>(mDbController == <span class="hljs-keyword">null</span>){
        synchronized (DbController.class){
            <span class="hljs-keyword">if</span>(mDbController == <span class="hljs-keyword">null</span>){
                mDbController = <span class="hljs-keyword">new</span> DbController(context);
            }
        }
    }
    <span class="hljs-keyword">return</span> mDbController;
}
<span class="hljs-comment">/**
 * 初始化
 * <span class="hljs-doctag">@param</span> context
 */</span>
<span class="hljs-keyword">public</span> DbController(Context context) {
    this.context = context;
    mHelper = <span class="hljs-keyword">new</span> DaoMaster.DevOpenHelper(context,<span class="hljs-string">"person.db"</span>, <span class="hljs-keyword">null</span>);
    mDaoMaster =<span class="hljs-keyword">new</span> DaoMaster(getWritableDatabase());
    mDaoSession = mDaoMaster.newSession();
    personInforDao = mDaoSession.getPersonInforDao();
}
<span class="hljs-comment">/**
 * 获取可读数据库
 */</span>
<span class="hljs-keyword">private</span> SQLiteDatabase getReadableDatabase(){
    <span class="hljs-keyword">if</span>(mHelper == <span class="hljs-keyword">null</span>){
        mHelper = <span class="hljs-keyword">new</span> DaoMaster.DevOpenHelper(context,<span class="hljs-string">"person.db"</span>,<span class="hljs-keyword">null</span>);
    }
    SQLiteDatabase db =mHelper.getReadableDatabase();
    <span class="hljs-keyword">return</span> db;
}

<span class="hljs-comment">/**
 * 获取可写数据库
 * <span class="hljs-doctag">@return</span>
 */</span>
<span class="hljs-keyword">private</span> SQLiteDatabase getWritableDatabase(){
    <span class="hljs-keyword">if</span>(mHelper == <span class="hljs-keyword">null</span>){
        mHelper =<span class="hljs-keyword">new</span> DaoMaster.DevOpenHelper(context,<span class="hljs-string">"person.db"</span>,<span class="hljs-keyword">null</span>);
    }
    SQLiteDatabase db = mHelper.getWritableDatabase();
    <span class="hljs-keyword">return</span> db;
}

<span class="hljs-comment">/**
 * 会自动判定是插入还是替换
 * <span class="hljs-doctag">@param</span> personInfor
 */</span>
<span class="hljs-keyword">public</span> void insertOrReplace(PersonInfor personInfor){
    personInforDao.insertOrReplace(personInfor);
}
<span class="hljs-comment">/**插入一条记录,表里面要没有与之相同的记录
 *
 * <span class="hljs-doctag">@param</span> personInfor
 */</span>
<span class="hljs-keyword">public</span> long insert(PersonInfor personInfor){
  <span class="hljs-keyword">return</span>  personInforDao.insert(personInfor);
}

<span class="hljs-comment">/**
 * 更新数据
 * <span class="hljs-doctag">@param</span> personInfor
 */</span>
<span class="hljs-keyword">public</span> void update(PersonInfor personInfor){
    PersonInfor mOldPersonInfor = personInforDao.queryBuilder().where(PersonInforDao.Properties.Id.eq(personInfor.getId())).build().unique();<span class="hljs-comment">//拿到之前的记录</span>
    <span class="hljs-keyword">if</span>(mOldPersonInfor !=<span class="hljs-keyword">null</span>){
        mOldPersonInfor.setName(<span class="hljs-string">"张三"</span>);
        personInforDao.update(mOldPersonInfor);
    }
}
<span class="hljs-comment">/**
 * 按条件查询数据
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">List</span>&lt;PersonInfor&gt; searchByWhere(String wherecluse){
    <span class="hljs-keyword">List</span>&lt;PersonInfor&gt;personInfors = (<span class="hljs-keyword">List</span>&lt;PersonInfor&gt;) personInforDao.queryBuilder().where(PersonInforDao.Properties.Name.eq(wherecluse)).build().unique();
    <span class="hljs-keyword">return</span> personInfors;
}
<span class="hljs-comment">/**
 * 查询所有数据
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">List</span>&lt;PersonInfor&gt; searchAll(){
    <span class="hljs-keyword">List</span>&lt;PersonInfor&gt;personInfors=personInforDao.queryBuilder().<span class="hljs-keyword">list</span>();
    <span class="hljs-keyword">return</span> personInfors;
}
<span class="hljs-comment">/**
 * 删除数据
 */</span>
<span class="hljs-keyword">public</span> void delete(String wherecluse){
    personInforDao.queryBuilder().where(PersonInforDao.Properties.Name.eq(wherecluse)).buildDelete().executeDeleteWithoutDetachingEntities();
}

}

看看我们的MainActivity

public class MainActivity extends AppCompatActivity {
<span class="hljs-keyword">private</span> Button Add,Delete,Update,Search;
<span class="hljs-keyword">private</span> DbController mDbController;
<span class="hljs-keyword">private</span> PersonInfor personInfor1,personInfor2,personInfor3,personInfor4;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> insertTipId;
<span class="hljs-keyword">private</span> TextView dataArea;
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(Bundle savedInstanceState)</span> </span>{
    <span class="hljs-keyword">super</span>.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDbController = DbController.getInstance(MainActivity.<span class="hljs-keyword">this</span>);
    initView();
    Envent();
    similateData();
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">similateData</span><span class="hljs-params">()</span> </span>{
    personInfor1 = <span class="hljs-keyword">new</span> PersonInfor(<span class="hljs-keyword">null</span>,<span class="hljs-string">"001"</span>,<span class="hljs-string">"王大宝"</span>,<span class="hljs-string">"男"</span>);
    personInfor2 = <span class="hljs-keyword">new</span> PersonInfor(<span class="hljs-keyword">null</span>,<span class="hljs-string">"002"</span>,<span class="hljs-string">"李晓丽"</span>,<span class="hljs-string">"女"</span>);
    personInfor3 = <span class="hljs-keyword">new</span> PersonInfor(<span class="hljs-keyword">null</span>,<span class="hljs-string">"003"</span>,<span class="hljs-string">"王麻麻"</span>,<span class="hljs-string">"男"</span>);
    personInfor4 = <span class="hljs-keyword">new</span> PersonInfor(<span class="hljs-keyword">null</span>,<span class="hljs-string">"004"</span>,<span class="hljs-string">"王大锤"</span>,<span class="hljs-string">"女"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Envent</span><span class="hljs-params">()</span> </span>{

    Add.setOnClickListener(<span class="hljs-keyword">new</span> View.OnClickListener() {
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onClick</span><span class="hljs-params">(View v)</span> </span>{
            <span class="hljs-comment">//Add</span>
           mDbController.insertOrReplace(personInfor1);

           mDbController.insertOrReplace(personInfor2);

           mDbController.insertOrReplace(personInfor3);

           mDbController.insertOrReplace(personInfor4);

            showDataList();
        }
    });
    Delete.setOnClickListener(<span class="hljs-keyword">new</span> View.OnClickListener() {
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onClick</span><span class="hljs-params">(View v)</span> </span>{
            <span class="hljs-comment">//Delete</span>
            mDbController.delete(<span class="hljs-string">"王麻麻"</span>);

            showDataList();
        }
    });

    Update.setOnClickListener(<span class="hljs-keyword">new</span> View.OnClickListener() {
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onClick</span><span class="hljs-params">(View v)</span> </span>{
            <span class="hljs-comment">//Update</span>
            mDbController.update(personInfor1);

            showDataList();
        }
    });

    Search.setOnClickListener(<span class="hljs-keyword">new</span> View.OnClickListener() {
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onClick</span><span class="hljs-params">(View v)</span> </span>{
            <span class="hljs-comment">//Search</span>
            showDataList();
        }
    });
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">showDataList</span><span class="hljs-params">()</span> </span>{
    StringBuilder sb = <span class="hljs-keyword">new</span> StringBuilder();
   List&lt;PersonInfor&gt;personInfors = mDbController.searchAll();
   <span class="hljs-keyword">for</span>(PersonInfor personInfor:personInfors){
      <span class="hljs-comment">// dataArea.setText("id:"+p);</span>
       sb.append(<span class="hljs-string">"id:"</span>).append(personInfor.getId())
         .append(<span class="hljs-string">"perNo:"</span>).append(personInfor.getPerNo())
         .append(<span class="hljs-string">"name:"</span>).append(personInfor.getName())
         .append(<span class="hljs-string">"sex:"</span>).append(personInfor.getSex())
         .append(<span class="hljs-string">"\n"</span>);
   }
   dataArea.setText(sb.toString());
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">initView</span><span class="hljs-params">()</span> </span>{

    Add = findViewById(R.id.Add);

    Delete = findViewById(R.id.Delete);

    Update = findViewById(R.id.Update);

    Search = findViewById(R.id.Search);

    dataArea= findViewById(R.id.tips);

}

}

代码说明:

细心的同学可以看到我们已经不用再使用创建数据库的sql语言了,因为GreenDao框架已经帮我们做了,通过之前的方式创建数据库过程当中还有可能出现一些莫名其妙的错误。我们只要定义出实体就可以了,从代码中可以看到我们创建了一个person.db的数据库。其实与我们平常操作就是这个Dao,这个框架会根据不同的数据实体对应生成不同的Dao,通过这个Dao我们就可以调用相应的接口去完成增删改查。

Demo简单展示

插入数据

add.PNG

更新数据

update.PNG

删除数据

delete.PNG

删除了王麻麻。

查询数据

search.PNG

GreenDao的介绍和使用就到此为止了,这个框架很方便,值得一用。

      </div>
    </div>

转自:https://www.jianshu.com/p/967d402d411d

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页