添加依赖
1,首先在根目录的build.gradle中添加
buildscript {
repositories {
google()
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}
2,在module的build.gradle中添加
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
dependencies {
compile 'org.greenrobot:greendao:3.2.2' // add library
}
3,自定义路径
在module的build.gradle中添加
greendao {
schemaVersion 1
//daoPackage 'com.wtk.greendao.gen'
//targetGenDir 'src/main/java'
}
schemaVersion--> 指定数据库schema版本号
daoPackage --> dao的包名,包名默认是entity所在的包;可用默认
targetGenDir --> 生成数据库文件的目录;可用默认
4,创建对象然后编译工程
@Entity
public class User {
@Id
private Long id;
private String name;
private int age;
}
5,访问数据库
DaoMaster.DevOpenHelper helper=new DaoMaster.DevOpenHelper(this,"test",null);
DaoMaster master=new DaoMaster(helper.getWritableDatabase());
DaoSession daoSession=master.newSession();
User user=new User();
user.setAge(26);
user.setName("wang");
long result=daoSession.getUserDao().insert(user); // 插入数据
Toast.makeText(this, "result:" + result, Toast.LENGTH_SHORT).show();
List<User> lists=daoSession.getUserDao().queryBuilder().list();
for(User user1 : lists){
Log.d("MainActivity", "user1:" + user1); // 读取打印数据
}
数据库升级
升级数据库的原理是:创建临时表,原表数据插入临时表,删除原表,创建新表,临时表数据复制到新表,删除临时表
因此我用了一个工具类MigrationHelper和MyOpenHelper
<MyOpenHelper.java>
public class MyOpenHelper extends DaoMaster.OpenHelper {
public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
//更改过的实体类(新增的不用加) 更新UserDao文件 可以添加多个 XXDao.class 文件
// MigrationHelper.getInstance().migrate(db, UserDao.class,XXDao.class);
MigrationHelper.getInstance().migrate(db,UserDao.class);
}
}
访问数据库时
helper=new MyOpenHelper(BaseApplication.getContext(),DB_NAME,null);
master=new DaoMaster(helper.getWritableDatabase());
daoSession=master.newSession();