Hello greenDAO(SQLite)

一、配置Gradle Scripts:

1.1、build.gradle(Project:*****)

buildscript {
repositories {
google()
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'//3.3.2 会告警
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}

1.2、build.gradle(Module:app)

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin greendao {
schemaVersion //数据库版本号
daoPackage 'com.trysqlite.greenDAO' // 设置包名(这里自己定义一下你的命名空间位置)
targetGenDir 'src/main/java' //设置 生成代码位置
generateTests false //设置为true以自动生成单元测试。
// targetGenDirTests 'src/main/java' //应存储生成的单元测试的基本目录。默认为 src / androidTest / java。
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3' 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'
implementation 'org.greenrobot:greendao-generator:3.0.0'
}

二、创建存储对象类(记住要@Entity,这样才会被构建相对应的操作类):

@Entity
public class teacher {
@Id(autoincrement = true)
Long id;
  @Property(nameInDb = "name") //设置了,数据库中的表格属性名为"name",如果不设置,数据库中表格属性名为"NAME"
  private String name;
}

三、菜单栏选择Build->Make Project

这里将生成:

  • DaoMaster:使用GreenDAO的入口点
  • DaoSession:管理特定架构的所有可用DAO对象:说白了就是增删查改数据库操作
  • teacherDao:数据访问对象(第二部写的实体类)

四、新建一个继承Application的类,对GreenDao进行初始化

public class MyApplication extends Application {
private static DaoSession daoSession; @Override
public void onCreate() {
super.onCreate(); //进入程序时初始化数据库
settupDatabase();
}
private void settupDatabase() {
//创建数据库
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "its_android.db", null);
//获取可写数据库
SQLiteDatabase db = helper.getWritableDatabase();
//获取数据库对象
DaoMaster daoMaster = new DaoMaster(db);
//获取Dao对象管理者
daoSession = daoMaster.newSession();
} public static DaoSession getDaoInstant() {
return daoSession;
}
}

五、做个预处理好的DBHelper

public class DBHelper {
static DaoSession daoSession = app.getDaoInstant(); //增
public void Addteacher(teacher teacher) {
daoSession.getTeacherDao().insert(teacher);
} //删
public void Deleteteacher(teacher teacher) {
daoSession.getTeacherDao().delete(teacher);
} //查
public List<teacher> Queryteacher(teacher teacher) {
QueryBuilder<teacher> qb = daoSession.queryBuilder(teacher.class);
QueryBuilder<teacher> teacherQueryBuilder = qb.where(teacherDao.Properties.Name.eq("一")).orderAsc(teacherDao.Properties.Name);
List<teacher> teacherList = teacherQueryBuilder.list(); //查出当前对应的数据
return teacherList;
} //改
public void Updateteacher(teacher teacher) {
daoSession.getTeacherDao().update(teacher);
} }
上一篇:7个你可能不认识的CSS单位:rem vh vw vmin vmax ex ch


下一篇:Android DevArt5:如何在Android中创建多线程?