GreenDao数据库
程序员文章站
2024-03-21 10:08:46
...
先导入依赖
在总的里面
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
Model里面
最上面
apply plugin: 'org.greenrobot.greendao' // apply plugin
greendao {
schemaVersion 1 //数据库版本号
daoPackage 'com.example.weekone.db'
// 设置DaoMaster、DaoSession、Dao 包名
targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
generateTests false //设置为true以自动生成单元测试。
targetGenDirTests 'src/main/java' //应存储生成的单元测试的基本目录。默认为 src / androidTest / java。
}
implementation 'org.greenrobot:greendao:3.2.2' // add library
Appliction中
public class MApp extends Application {
private static DaoSession daoSession;
public static DaoSession getDaoSession() {
return daoSession;
}
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "aserbao.db");
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
}
在需要的bean头部加入
@Entity
MainActivity中
private DaoSession daoSession = MApp.getDaoSession();
查询
for (int i = 0; i < results1.size(); i++) {
ResultsBean resultsBean = new ResultsBean();
resultsBean.setCover(""+results1.get(i).getCover());
resultsBean.setTitle(""+results1.get(i).getTitle());
this.daoSession.insertOrReplace(resultsBean);
}
//增加
List<ResultsBean> resultsBeans = daoSession.loadAll(ResultsBean.class);
for (ResultsBean bean:resultsBeans){
Log.e("zlx",""+bean.getTitle());
}