您的位置:首页 > 移动开发 > Android开发

Android 数据库框架GreenDao食用练习

2017-12-28 18:09 651 查看
从做手机开发转到互联网,难免会有很多之前用不到的东西,这些暂时可能也还用不到,但补一下第三方库的食用经验也是不错的,亡羊补牢为时不晚!

先研究一下GreenDao数据库框架吧。Github地址:GreenDao

学习自Android框架之路——GreenDao3.2.2的使用

首先创建一个新的app,然后根据GitHub上给出的导入工程方法:

greenDAO is available on Maven Central. Please ensure that you are using the latest versions by checking here and here

在此查看到的最新版为3.2.2

Add the following Gradle configuration to your Android project:

在根Gradle(Project gradle)中添加下面代码段

// In your root build.gradle file:
buildscript {
repositories {
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}


在app的gradle(module app gradle)中添加下面代码

// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin

dependencies {
compile 'org.greenrobot:greendao:3.2.2' // add library
}


而后配置schema的版本

greendao {
schemaVersion 1
daoPackage 'com.example.grant.greendaotest.greendao'
targetGenDir 'src/main/java'
}


而后点击右上角的sync now,等待Android studio自动同步。

食用开始:

先创建一个名为Entity的包,而后创建一个Students类

如下

package com.example.grantz.greendaotest.Entity;

/**
* Created by GrantZ on 2017/12/28.
*/

public class Students {

private  String name;
private  int age;
private  int score;
private  String imgUrl;

}


为其添加注解@Entity,学习P???Q 的博客可知,注解的相关含义

注解后如下:

@Entity
public class Students {

@NotNull
private  String name;

@Id(autoincrement = true)//@Id表示将其作为实体ID autoincrement表示为自增
private  long id;
private  int age;
private  int score;
private  String imgUrl;

/*
@Entity:将我们的java普通类变为一个能够被greenDAO识别的数据库类型的实体类;
@nameInDb:在数据库中的名字,如不写则为实体中类名;
@Id:选择一个long / Long属性作为实体ID。 在数据库方面,它是主键。 参数autoincrement是设置ID值自增;
@NotNull:使该属性在数据库端成为“NOT NULL”列。 通常使用@NotNull标记原始类型(long,int,short,byte)是有意义的;
@Transient:表明这个字段不会被写入数据库,只是作为一个普通的java类字段,用来临时存储数据的,不会被持久化。
*/

}


点击Build>make project 可见greendao自动为我们生成的相关内容。


而后按照大佬的做法创建了manager和Util类Android框架之路——GreenDao3.2.2的使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 android greendao