Android GreenDao数据库基础讲解

  • Post author:
  • Post category:其他



一.GreenDao数据库简介


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




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


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


二.GreenDao 优点



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


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


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


4.简洁易用的API。


三.GreenDao数据库使用


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
}


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
}


2.创建实体类


步骤


<1> 创建类名为People的普通类并创建所需要的属性

public class People {

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

}



id 必须为Long


<2> 类名上@Entity




<3> Make Project


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

@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  自增




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


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




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;
    }

}


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<UserInfo> list=queryUserList();
                StringBuilder sbBuilder = new StringBuilder();
                for(int i=0;i<list.size();i++){
                    UserInfo userInfo=list.get(i);
                    Long id=userInfo.getId();
                    String name=userInfo.getName();
                    String age=userInfo.getAge();
                    sbBuilder.append("ID:" + id + "\n");
                    sbBuilder.append("姓名:" + name + "\n\n");
                    sbBuilder.append("年龄:" + age + "\n\n");
                }
                textView.setText(sbBuilder.toString());
                break;
            default:
                break;
        }
    }

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

    public void insertUser() {
        UserInfo userInfo=new UserInfo();
        userInfo.setId(id);
        userInfo.setName("张三");
        userInfo.setAge("29");
        UserInfoDao userInfoDao= MyApplication.getDaoInstant().getUserInfoDao();
        userInfoDao.insert(userInfo);
    }

    /**
     * 删除一条记录
     */

    public void deleteUser() {
        UserInfo userInfo=new UserInfo();
        userInfo.setId(id);
        userInfo.setName("张三");
        userInfo.setAge("29");
        UserInfoDao userInfoDao= MyApplication.getDaoInstant().getUserInfoDao();
        userInfoDao.delete(userInfo);
    }

    /**
     * 更新一条记录
     */

    public void updateUser() {
        UserInfo userInfo=new UserInfo();
        userInfo.setId(id);
        userInfo.setName("张三更新");
        userInfo.setAge("29");
        UserInfoDao userInfoDao= MyApplication.getDaoInstant().getUserInfoDao();
        userInfoDao.update(userInfo);
    }

    /**
     * 查询数据列表
     */

    public List<UserInfo> queryUserList() {
        UserInfoDao userInfoDao= MyApplication.getDaoInstant().getUserInfoDao();
        QueryBuilder<UserInfo> qb = userInfoDao.queryBuilder();
        List<UserInfo> list = qb.list();
        return list;
    }

}


5.结果


增——>查


删——>查


改——>查




注意


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


插入数据

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

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<UserInfo> list=new ArrayList<>();
    list.add(userInfo);
    list.add(userInfo1);
    list.add(userInfo2);
    list.add(userInfo3);

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


结果




代码链接:

https://github.com/wujianning/AndroidDBDemo



版权声明:本文为weixin_37730482原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。