[关闭]
@linux1s1s 2016-12-01T10:26:28.000000Z 字数 6853 阅读 1875

Android ORM - GreenDAO

AndroidRefine 2016-11


系列博文
Android ORM - GreenDAO
Android ORM - OrmLite

ORM/DAO

此处输入图片的描述

Demo

下面以一个简单的Demo演示一下如何使用GreenDAO

配置和资源文件

AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="okhttp.mutex.com.orm_demo">
  4. <application
  5. android:name=".ORMApplication"
  6. android:allowBackup="true"
  7. android:icon="@mipmap/ic_launcher"
  8. android:label="@string/app_name"
  9. android:supportsRtl="true"
  10. android:theme="@style/AppTheme">
  11. <activity android:name=".MainActivity">
  12. <intent-filter>
  13. <action android:name="android.intent.action.MAIN" />
  14. <category android:name="android.intent.category.LAUNCHER" />
  15. </intent-filter>
  16. </activity>
  17. </application>
  18. </manifest>
Top-level build.gradle
  1. // Top-level build file where you can add configuration options common to all sub-projects/modules.
  2. buildscript {
  3. repositories {
  4. jcenter()
  5. mavenCentral()
  6. }
  7. dependencies {
  8. classpath 'com.android.tools.build:gradle:2.2.2'
  9. classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
  10. // NOTE: Do not place your application dependencies here; they belong
  11. // in the individual module build.gradle files
  12. }
  13. }
  14. allprojects {
  15. repositories {
  16. jcenter()
  17. }
  18. }
  19. task clean(type: Delete) {
  20. delete rootProject.buildDir
  21. }
Second-level build.gradle
  1. apply plugin: 'com.android.application'
  2. apply plugin: 'org.greenrobot.greendao'
  3. android {
  4. compileSdkVersion 24
  5. buildToolsVersion "24.0.0"
  6. defaultConfig {
  7. applicationId "okhttp.mutex.com.orm_demo"
  8. minSdkVersion 15
  9. targetSdkVersion 24
  10. versionCode 1
  11. versionName "1.0"
  12. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  13. }
  14. buildTypes {
  15. release {
  16. minifyEnabled false
  17. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  18. }
  19. }
  20. greendao{
  21. schemaVersion 1
  22. daoPackage 'com.admom.mygreendaotest'
  23. targetGenDir 'src/main/java'
  24. }
  25. }
  26. dependencies {
  27. compile fileTree(include: ['*.jar'], dir: 'libs')
  28. androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  29. exclude group: 'com.android.support', module: 'support-annotations'
  30. })
  31. compile 'com.android.support:appcompat-v7:24.2.1'
  32. testCompile 'junit:junit:4.12'
  33. compile 'org.greenrobot:greendao:3.2.0'
  34. }

以上配置重点关注一下信息:
- 加入greendao插件
- 配置greendao生成代码的目录地址,包名以及版本号
- 配置greendao的依赖地址

另外以上配置greendao信息的相关字段简要说明如下:

  • schemaVersion: 数据库schema版本,也可以理解为数据库版本号
  • daoPackage:设置DaoMaster 、DaoSession、Dao包名
  • targetGenDir:设置DaoMaster 、DaoSession、Dao目录
  • targetGenDirTest:设置生成单元测试目录
  • generateTests:设置自动生成单元测试用例

源码

先生成POJO类,greendao通过注解的形式自动生成DAO类

Info.java
  1. package okhttp.mutex.com.orm_demo;
  2. import org.greenrobot.greendao.annotation.Entity;
  3. import org.greenrobot.greendao.annotation.Id;
  4. import org.greenrobot.greendao.annotation.Generated;
  5. @Entity
  6. public class Info {
  7. @Id(autoincrement = true)
  8. private long id;
  9. private String name;
  10. private int age;
  11. ...
  12. }

编译完以后会自动生成DaoMaster, DaoSession, XXXDao等类,并把这些类自动放到指定的目录和包名下,如图所示:

此处输入图片的描述

我们需要进一步了解注解的相关意思

  • 实体@Entity注解
    schema:告知GreenDao当前实体属于哪个schema
    active:标记一个实体处于活动状态,活动实体有更新、删除和刷新方法
    nameInDb:在数据中使用的别名,默认使用的是实体的类名
    indexes:定义索引,可以跨越多个列
    createInDb:标记创建数据库表
  • @Id :主键 Long型,可以通过@Id(autoincrement = true)设置自增长
  • @Property:设置一个非默认关系映射所对应的列名,默认是的使用字段名 举例:@Property (nameInDb="name")
  • @NotNul:设置数据库表当前列不能为空
  • @Transient :添加次标记之后不会生成数据库表的列
  • @Index:使用@Index作为一个属性来创建一个索引,通过name设置索引别名,也可以通过unique给索引添加约束
  • @Unique:向数据库列添加了一个唯一的约束
  • @ToOne:定义与另一个实体(一个实体对象)的关系
  • @ToMany:定义与多个实体对象的关系
GreenDAOManager.java
  1. package okhttp.mutex.com.orm_demo;
  2. import android.content.Context;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import com.admom.mygreendaotest.DaoMaster;
  5. public class GreenDAOManager {
  6. private static GreenDAOManager sINSTANCE;
  7. private final DaoMaster.DevOpenHelper mHelper;
  8. private GreenDAOManager(Context context, String name) {
  9. mHelper = new DaoMaster.DevOpenHelper(context, name, null);
  10. }
  11. public static void createInstance(Context context, String name) {
  12. if (sINSTANCE == null) {
  13. synchronized (GreenDAOManager.class) {
  14. if (sINSTANCE == null) {
  15. sINSTANCE = new GreenDAOManager(context, name);
  16. }
  17. }
  18. }
  19. }
  20. public static GreenDAOManager getInstance() {
  21. return sINSTANCE;
  22. }
  23. public SQLiteDatabase getReadableDatabase() {
  24. return mHelper.getReadableDatabase();
  25. }
  26. public SQLiteDatabase getWritableDatabase() {
  27. return mHelper.getWritableDatabase();
  28. }
  29. }
InfoDAOHelper.java
  1. package okhttp.mutex.com.orm_demo;
  2. import com.admom.mygreendaotest.DaoMaster;
  3. import com.admom.mygreendaotest.DaoSession;
  4. import com.admom.mygreendaotest.InfoDao;
  5. import org.greenrobot.greendao.query.QueryBuilder;
  6. import java.util.List;
  7. public class InfoDAOHelper {
  8. private InfoDAOHelper() {
  9. //Do Nothing
  10. }
  11. /**
  12. * 插入一条数据
  13. *
  14. * @param info
  15. */
  16. public static void insertInfo(Info info) {
  17. if (info == null)
  18. return;
  19. InfoDao infoDao = obtainWritableInfoDao();
  20. infoDao.insert(info);
  21. }
  22. /**
  23. * 插入一组数据
  24. *
  25. * @param infoList
  26. */
  27. public static void insertInfo(List<Info> infoList) {
  28. if (infoList == null || infoList.isEmpty())
  29. return;
  30. InfoDao info = obtainWritableInfoDao();
  31. info.insertInTx(infoList);
  32. }
  33. /**
  34. * 删除一组数据
  35. *
  36. * @param info
  37. */
  38. public static void deleteInfo(Info info) {
  39. if (info == null)
  40. return;
  41. InfoDao dao = obtainWritableInfoDao();
  42. dao.delete(info);
  43. }
  44. /**
  45. * 更新一组数据
  46. *
  47. * @param info
  48. */
  49. public static void update(Info info) {
  50. if (info == null)
  51. return;
  52. InfoDao dao = obtainWritableInfoDao();
  53. dao.update(info);
  54. }
  55. /**
  56. * 查询数据列表
  57. *
  58. * @return
  59. */
  60. public static List<Info> queryInfoList() {
  61. InfoDao dao = obtainReadableInfoDao();
  62. QueryBuilder<Info> builder = dao.queryBuilder();
  63. return builder.list();
  64. }
  65. /**
  66. * 查询符合条件的数据列表
  67. *
  68. * @param age
  69. * @return
  70. */
  71. public static List<Info> queryInfoList(int age) {
  72. InfoDao dao = obtainReadableInfoDao();
  73. QueryBuilder<Info> builder = dao.queryBuilder();
  74. builder.where(InfoDao.Properties.Age.eq(age)).orderAsc(InfoDao.Properties.Age);
  75. return builder.list();
  76. }
  77. private static InfoDao obtainWritableInfoDao() {
  78. DaoMaster master = new DaoMaster(GreenDAOManager.getInstance().getWritableDatabase());
  79. DaoSession session = master.newSession();
  80. return session.getInfoDao();
  81. }
  82. private static InfoDao obtainReadableInfoDao() {
  83. DaoMaster master = new DaoMaster(GreenDAOManager.getInstance().getReadableDatabase());
  84. DaoSession session = master.newSession();
  85. return session.getInfoDao();
  86. }
  87. }
ORMApplication.java
  1. package okhttp.mutex.com.orm_demo;
  2. import android.app.Application;
  3. public class ORMApplication extends Application {
  4. @Override
  5. public void onCreate() {
  6. super.onCreate();
  7. GreenDAOManager.createInstance(this, "db_test_name_4");
  8. }
  9. }
MainActivity.java
  1. package okhttp.mutex.com.orm_demo;
  2. import android.os.Bundle;
  3. import android.support.v7.app.AppCompatActivity;
  4. import android.util.Log;
  5. import java.util.List;
  6. public class MainActivity extends AppCompatActivity {
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_main);
  11. initInfo();
  12. queryOri();
  13. queryOri(21);
  14. updateOri();
  15. deleteOri();
  16. }
  17. private void updateOri() {
  18. Info info = new Info(1, "name" + 1, 2 + 20);
  19. InfoDAOHelper.update(info);
  20. queryOri(22);
  21. }
  22. private void deleteOri() {
  23. Info info = new Info(1, "name" + 1, 1 + 20);
  24. InfoDAOHelper.deleteInfo(info);
  25. queryOri(21);
  26. }
  27. private void queryOri(int age) {
  28. List<Info> list = InfoDAOHelper.queryInfoList(age);
  29. for (Info info : list) {
  30. Log.w("mutex", age + " is : " + info.toString());
  31. }
  32. }
  33. private void queryOri() {
  34. List<Info> list = InfoDAOHelper.queryInfoList();
  35. for (Info info : list) {
  36. Log.i("mutex", info.toString());
  37. }
  38. }
  39. private void initInfo() {
  40. for (int i = 0; i < 10; i++) {
  41. Info info = new Info(i, "name" + i, i + 20);
  42. InfoDAOHelper.insertInfo(info);
  43. }
  44. }
  45. }

验证结果

此处输入图片的描述

以上验证符合预期。

参考文章:
GreenDAO Website Github Doc Ori
OrmLite Website Github

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注