一:将GreenDao引入项目中
需要在两个地方添加配置:
1:在Project–>budld.gradle中配置如下:
dependencies {
classpath 'com.android.tools.build:gradle:3.5.1'
//这里是需要配置的地方
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
}
2:在Modle–>build.gradle中配置:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion 28
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.greendaodemo003"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
greendao {
schemaVersion 1 //当前数据库版本
targetGenDir 'src/main/java' //生成DaoMaster类文件夹
}
}
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' // 添加库
}
配置完成后点击sync now同步即可
编写实体类
以school为例:
@Entity
public class School {
@Id
private Long id;
private String name;
}
写完实体类可以运行一下,DaoMaster等文件包会自动生成

CRUD
使用DaoSession直接根据对象进行操作
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "school", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
final DaoSession session = daoMaster.newSession();
- 增:
School school = new School((long)1,"辽宁金融职业学院");
session.insert(school);
- 删:
School school = new School((long)1,"fly");
session.delete(school);
- 改:
School school = new School((long)1,"ffffffffly");
session.update(school);
- 查(查询所有):
List<School> school = session.loadAll(School.class);
String schoolName = "";
for (int i = 0; i < school.size(); i++) {
schoolName += school.get(i).getName() + ",";
Log.d("chen",schoolName);
}
网友评论