Android - greenDao

导包

  1. rootProject中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    buildscript {

    repositories {
    google()
    jcenter()
    mavenCentral() // greenDao 111111111111
    }
    dependencies {
    classpath 'com.android.tools.build:gradle:3.1.2'

    classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // greenDao 2222222
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    }
    }

    allprojects {
    repositories {
    google()
    jcenter()
    maven { url "https://jitpack.io" }//greenDao update 333333333
    }
    }

    task clean(type: Delete) {
    delete rootProject.buildDir
    }
  2. project的build.gradle

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    apply plugin: 'com.android.application'
    apply plugin: 'org.greenrobot.greendao'//greenDao 111111111

    android {
    compileSdkVersion 28
    defaultConfig {
    applicationId "com.example.kj_greendao"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
    release {
    minifyEnabled false
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    }
    }
    //grendao 2222222222
    greendao {
    schemaVersion 7 //数据库版本号
    daoPackage 'com.example.kj_greendao.gen'//指定生成的Daomaster ,daosession,xxDao的位置
    targetGenDir 'src/main/java'
    }

    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 3333333333333
    api 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v2.1.0'//greeDaoUpDate 44444444444
    }

使用

  1. 定义Bean,之后build自动生成如下代码,同时生成了三个dao相关类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    package com.example.kj_greendao;

    import org.greenrobot.greendao.annotation.Entity;
    import org.greenrobot.greendao.annotation.Id;
    import org.greenrobot.greendao.annotation.Generated;

    @Entity
    public class StudentBean {
    //注意此处必须是Long,而不是long
    @Id
    private Long id;

    private String name;

    private int age;

    private boolean sex;

    private String test;

    @Override
    public String toString() {
    return "StudentBean{" +
    "id=" + id +
    ", name='" + name + '\'' +
    ", age=" + age +
    ", sex=" + sex +
    ", test='" + test + '\'' +
    '}';
    }

    @Generated(hash = 1767927902)
    public StudentBean(Long id, String name, int age, boolean sex, String test) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.test = test;
    }

    @Generated(hash = 2097171990)
    public StudentBean() {
    }

    public Long getId() {
    return this.id;
    }

    public void setId(Long id) {
    this.id = id;
    }

    public String getName() {
    return this.name;
    }

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

    public int getAge() {
    return this.age;
    }

    public void setAge(int age) {
    this.age = age;
    }

    public boolean getSex() {
    return this.sex;
    }

    public void setSex(boolean sex) {
    this.sex = sex;
    }

    public String getTest() {
    return this.test;
    }

    public void setTest(String test) {
    this.test = test;
    }
    }
  1. 自定义OpenHelper 继承自DaoMaster.OpenHelper,重写onUpgrade方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    package com.example.kj_greendao;

    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;

    import com.example.kj_greendao.gen.DaoMaster;
    import com.example.kj_greendao.gen.StudentBeanDao;
    import com.github.yuweiguocn.library.greendao.MigrationHelper;

    import org.greenrobot.greendao.database.Database;

    public class GreenDaoOpenHelper extends DaoMaster.OpenHelper {
    public GreenDaoOpenHelper(Context context, String name) {
    super(context, name);
    }

    public GreenDaoOpenHelper(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);
    }
    },StudentBeanDao.class);
    }
    }
  1. 初始化以及增删改查

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    package com.example.kj_greendao;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;

    import com.example.kj_greendao.gen.DaoMaster;
    import com.example.kj_greendao.gen.DaoSession;
    import com.example.kj_greendao.gen.StudentBeanDao;

    import org.greenrobot.greendao.database.Database;
    import org.greenrobot.greendao.query.Query;

    import java.util.List;

    public class GreendaoHomeAct extends AppCompatActivity {

    private TextView mTv;

    private Query<StudentBean> mStudentAllItemBuild;
    private long id = 1;
    private StudentBeanDao mStudentBeanDao;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_greendao_home);
    mTv = (TextView) this.findViewById(R.id.tv);
    (findViewById(R.id.bt_init)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    GreenDaoOpenHelper greenDaoOpenHelper = new GreenDaoOpenHelper(GreendaoHomeAct.this, "kbjay-db");
    Database db = greenDaoOpenHelper.getWritableDb();
    DaoSession daoSession = new DaoMaster(db).newSession();
    mStudentBeanDao = daoSession.getStudentBeanDao();
    mStudentAllItemBuild = mStudentBeanDao.queryBuilder().build();
    print();
    }
    });
    (findViewById(R.id.bt_add)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    StudentBean wzq = new StudentBean();
    wzq.setAge(10);
    wzq.setName("wzq"+(id++));
    mStudentBeanDao.insert(wzq);
    print();
    }
    });
    (findViewById(R.id.bt_change)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    if (mStudentAllItemBuild.list() != null && mStudentAllItemBuild.list().size() > 0) {
    StudentBean studentBean = mStudentAllItemBuild.list().get(0);
    studentBean.setAge(18);
    mStudentBeanDao.update(studentBean);
    }
    print();
    }
    });
    (findViewById(R.id.bt_delete)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    if (mStudentAllItemBuild.list() != null && mStudentAllItemBuild.list().size() > 0) {
    StudentBean studentBean = mStudentAllItemBuild.list().get(0);
    mStudentBeanDao.delete(studentBean);
    }
    print();
    }
    });
    (findViewById(R.id.bt_getAll)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    print();
    }
    });

    (findViewById(R.id.bt_search)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    List<StudentBean> list = mStudentBeanDao.queryBuilder().where(StudentBeanDao.Properties.Age.eq(18))
    .build().list();

    if (list != null && list.size() > 0) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < list.size(); i++) {
    sb.append(list.get(i).toString() + "\r\n");
    }
    mTv.setText(sb.toString());
    }else{
    mTv.setText("没有18岁的人!!!!");
    }
    }
    });
    (findViewById(R.id.bt_deletAll)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    mStudentBeanDao.deleteAll();
    print();
    }
    });
    (findViewById(R.id.bt_update)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    }
    });
    }

    public void print() {
    List<StudentBean> list = mStudentAllItemBuild.list();
    if (list != null && list.size() > 0) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < list.size(); i++) {
    sb.append(list.get(i).toString() + "\r\n");
    }
    mTv.setText(sb.toString());
    }else{
    mTv.setText("");
    }
    }
    }
  1. layout文件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".GreendaoHomeAct">

    <Button
    android:id="@+id/bt_init"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="初始化" />

    <Button
    android:id="@+id/bt_add"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="增加" />

    <Button
    android:id="@+id/bt_delete"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="删除" />

    <Button
    android:id="@+id/bt_change"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="修改" />

    <Button
    android:id="@+id/bt_search"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="查询" />

    <Button
    android:id="@+id/bt_getAll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="获取全部" />

    <Button
    android:id="@+id/bt_deletAll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="清空表" />
    <Button
    android:id="@+id/bt_update"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="数据库升级" />

    <TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4a4a4a"
    android:textColor="#fff" />
    </LinearLayout>

升级

核心思路:

  1. 建立一个临时表(由原表copy一份)

  2. 删除旧表

  3. 建立新表

  4. 将临时表的数据迁移到新表

测试:

  1. 修改数据库版本号
  2. bean中添加新字段,重新运行即可

关于greenDao

  1. DevOpenHelper:创建SQLite数据库的SQLiteOpenHelper的具体实现
  2. DaoMaster:GreenDao的顶级对象,作为数据库对象、用于创建表和删除表
  3. DaoSession:管理所有的Dao对象,Dao对象中存在着增删改查等API

数据库版本升级:https://github.com/yuweiguocn/GreenDaoUpgradeHelper

https://stackoverflow.com/questions/13373170/greendao-schema-update-and-data-migration/30334668#30334668

使用参考:https://github.com/greenrobot/greenDAO

http://greenrobot.org/files/greendao/javadoc/current/

Api文档:http://greenrobot.org/files/greendao/javadoc/current/