classpath ‘org.greenrobot:greendao-gradle-plugin:3.2.2’//添加插件
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
之后点击Sync Project
2.2. 在app的build.gradle中配置
apply plugin: ‘com.android.application’
apply plugin: ‘org.greenrobot.greendao’
之后在dependencies中添加依赖
dependencies {
implementation fileTree(dir: ‘libs’, include: [’*.jar’])
implementation ‘androidx.appcompat:appcompat:1.1.0’
implementation ‘androidx.constraintlayout:constraintlayout:1.1.3’
testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘androidx.test.ext:junit:1.1.1’
androidTestImplementation ‘androidx.test.espresso:espresso-core:3.2.0’
implementation ‘org.greenrobot:greendao:3.2.2’ // 添加依赖
}
之后配置数据库相关信息
greendao {
schemaVersion 1 //当前数据库版本
targetGendir ‘src/main/java’//指定生成代码的目录
daoPackage ‘com.lab.search’//生成代码到具体的包下
}
配置就完成了,之后点击Sync Now
在Sync时,出现了下载依赖很慢的事情,所以我在工程目录下的build.gradle将buildscript的repositories改成了
repositories {
google()
//jcenter()
maven{ url ‘http://maven.aliyun.com/nexus/content/groups/public/’}
}
以及
allprojects {
repositories {
google()
//jcenter()
maven{ url ‘http://maven.aliyun.com/nexus/content/groups/public/’}
}
}
把地址改成了阿里云的仓库,下载就快了。
二、使用greendao(1)
2.1. 创建一个实体类
在目录下创建一个Package名为bean,在bean包下面创建一个Java类,类为实体类,即仅有属性以及getter、setter、构造方法以及toString()方法的类,一个实体类则对应一张数据库的表,我将这个实体类取名为UserInfo,类中有id,userName,phoneNumber,address等属性
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
@Entity
public class UserInfo {
@Id
private Long id;
@Property(nameInDb = “user_name”)
private String userName;
@Property(nameInDb = “phone_number”)
private String phoneNumber;
@Property(nameInDb = “address”)
private String address;
}
在这里,我用了许多注解,而这些注解有什么作用呢?简单介绍一下在GreenDao中常用的一些注解
@Entity:将我们的java普通类变为一个能够被greenDAO识别的数据库类型的实体类,也就是将这个类标记为要映射到数据库的实体类
@Id&#