Android GreenDao数据库—基础详解

1.GreenDao数据库简介

 

greenDAO是一个对象关系映射(ORM)的框架,能够提供一个接口通过操作对象的方式去操作关系型数据库,它能够让你操作数据库时更简单、更方便。如下图所示:

 

Android GreenDao数据库—基础详解_第1张图片

 

官网地址:http://greenrobot.org/greendao

 

github:https://github.com/greenrobot/greenDAO

 

 

 

 

2.GreenDao 优点


2.1.性能高,号称Android最快的关系型数据库。

 

2.2.内存占用小 库文件比较小,小于100K,编译时间低,而且可以避免65K方法限制。

 

2.3.支持数据库加密  greendao支持SQLCipher进行数据库加密 。

 

2.4.简洁易用的API。

 

 

 

 

3.代码讲解

 

3.1.配置Gradle

 

根目录gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

 

Android GreenDao数据库—基础详解_第2张图片

 

 

app gradle

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

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.wjn.androiddbdemo"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    greendao {
        // 版本号
        schemaVersion 1
        //greendao输出dao的数据库操作实体类文件夹
        daoPackage 'com.wjn.androiddbdemo.greendao'
        //greenDao实体类包文件夹
        targetGenDir 'src/main/java'
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    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 'com.readystatesoftware.systembartint:systembartint:1.0.3'
    implementation 'org.greenrobot:greendao:3.2.2' // add library
}

 

Android GreenDao数据库—基础详解_第3张图片

 

Android GreenDao数据库—基础详解_第4张图片

 

Android GreenDao数据库—基础详解_第5张图片

 

 

3.2.创建实体类

 

步骤

 

3.2.1.创建类名为People的普通类并创建所需要的属性 

public class People {

    private Long id;
    private String name;
    private String height;
    private String weight;

}

id 必须为Long

 

 

3.2.2.类名上@Entity

 

 

3.2.3.Make Project

Android GreenDao数据库—基础详解_第6张图片

稍等片刻 后实体类 变成如下

@Entity
public class People {

    @Id(autoincrement = true)
    private Long id;
    private String name;
    private String height;
    private String weight;
    @Generated(hash = 516943684)
    public People(Long id, String name, String height, String weight) {
        this.id = id;
        this.name = name;
        this.height = height;
        this.weight = weight;
    }
    @Generated(hash = 1406030881)
    public People() {
    }
    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 String getHeight() {
        return this.height;
    }
    public void setHeight(String height) {
        this.height = height;
    }
    public String getWeight() {
        return this.weight;
    }
    public void setWeight(String weight) {
        this.weight = weight;
    }

}

 

注意:主键要添加autoincrement  自增

Android GreenDao数据库—基础详解_第7张图片

 

否则会报 does not have a single-column primary key 错误

 

 

 

设置的文件夹中会生成以下类

Android GreenDao数据库—基础详解_第8张图片

 

 

 

 

 

3.3.在Application中获取 DaoSession

public class MyApplication extends Application {

    private static DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        setupDatabase();
    }

    /**
     * 配置数据库
     */

    private void setupDatabase() {
        //创建数据库shop.db 创建SQLite数据库的SQLiteOpenHelper的具体实现
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "greendaodemo.db", null);
        //获取SQLiteDatabase对象
        SQLiteDatabase db = helper.getReadableDatabase();
        //获取数据库对象
        DaoMaster daoMaster = new DaoMaster(db);
        //获取dao对象管理者
        daoSession = daoMaster.newSession();
    }

    /**
     * 获取 DaoSession 外部调用
     * */

    public static DaoSession getDaoInstant() {
        return daoSession;
    }

}

 

 

 

3.4.Activity代码

public class GreenDaoActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView textView1;
    private TextView textView2;
    private TextView textView3;
    private TextView textView4;
    private TextView textView;
    private String string="123456";
    private Long id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_greendao);
        initView();
    }

    /**
     * 初始化各种View
     */

    private void initView() {
        //根据状态栏颜色来决定 状态栏背景 用黑色还是白色 true:是否修改状态栏字体颜色
        StatusBarUtil.setStatusBarMode(this, false, false, R.color.colorPrimary);
        textView1 = findViewById(R.id.activity_greendao_textview1);
        textView2 = findViewById(R.id.activity_greendao_textview2);
        textView3 = findViewById(R.id.activity_greendao_textview3);
        textView4 = findViewById(R.id.activity_greendao_textview4);
        textView = findViewById(R.id.activity_greendao_textview);
        textView1.setOnClickListener(this);
        textView2.setOnClickListener(this);
        textView3.setOnClickListener(this);
        textView4.setOnClickListener(this);

        id=Long.parseLong(string);

    }

    /**
     * 各种点击事件的方法
     */

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_greendao_textview1://增
                insertUser();
                break;
            case R.id.activity_greendao_textview2://删
                deleteUser();
                break;
            case R.id.activity_greendao_textview3://改
                updateUser();
                break;
            case R.id.activity_greendao_textview4://查
                List list=queryUserList();
                StringBuilder sbBuilder = new StringBuilder();
                for(int i=0;i queryUserList() {
        UserInfoDao userInfoDao= MyApplication.getDaoInstant().getUserInfoDao();
        QueryBuilder qb = userInfoDao.queryBuilder();
        List list = qb.list();
        return list;
    }

}

 

 

 

3.5.结果

 

3.5.1.增——>查

Android GreenDao数据库—基础详解_第9张图片

 

 

3.5.2.删——>查

Android GreenDao数据库—基础详解_第10张图片

 

 

3.5.3.改——>查

Android GreenDao数据库—基础详解_第11张图片

 

 

 

 

3.6.注意

主键设置了自增后 插入是就可以不用设置id

 

3.6.1.插入数据

/**
     * 插入一条记录
     */

    public void insertUser() {
        UserInfo userInfo=new UserInfo();
        userInfo.setName("张三");
        userInfo.setAge("29");

        UserInfo userInfo1=new UserInfo();
        userInfo1.setName("李四");
        userInfo1.setAge("39");

        UserInfo userInfo2=new UserInfo();
        userInfo2.setName("旺旺");
        userInfo2.setAge("19");

        UserInfo userInfo3=new UserInfo();
        userInfo3.setName("王伟");
        userInfo3.setAge("59");

        List list=new ArrayList<>();
        list.add(userInfo);
        list.add(userInfo1);
        list.add(userInfo2);
        list.add(userInfo3);

        UserInfoDao userInfoDao= MyApplication.getDaoInstant().getUserInfoDao();
        userInfoDao.insertInTx(list);
    }

 

 

3.6.2.结果

Android GreenDao数据库—基础详解_第12张图片

 

 

 

 

 

 

代码链接:https://github.com/wujianning/AndroidDBDemo

你可能感兴趣的:(Android,数据库)