GreenDao源码分析
GreenDao升级数据库原有数据
- 整个项目添加依赖:
buildscript {
repositories {
google()
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
- app 模块添加依赖
apply plugin: 'org.greenrobot.greendao' // apply plugin
android {
greendao {
schemaVersion 1//数据库版本
}
}
dependencies {
implementation 'org.greenrobot:greendao:3.2.2' // add library
}
- 写数据库实体类
//class名字Note为表名
@Entity
public class Note {
@Id
private Long id;
@NotNull
private String text;
@Generated(hash = 990389247)//自动生成的,下一步的时候会自动生成
public Note(Long id, @NotNull String text) {
this.id = id;
this.text = text;
}
@Generated(hash = 1272611929)//自动生成的,下一步的时候会自动生成
public Note() {
}
...get/set...
}
- Build->Make Project:
- 配置application(注意在清单配置中替换)
public class App extends Application {
private DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
//设置数据库名
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"test1");
Database db = helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
}
- 向数据库添加数据
public class MainActivity extends AppCompatActivity {
DaoSession daoSession;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaoSession daoSession =((App)getApplication()).getDaoSession();
new Thread(new Runnable() {
@Override
public void run() {
Note note = new Note();
note.setText("aaa");
daoSession.insert(note);
handler.sendEmptyMessage(0);
}
}).start();
}
@SuppressLint("HandlerLeak")
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0:
List<Note> list = daoSession.loadAll(Note.class);
for(Note note:list)Log.w("打印",note.getText());
break;
}
}
};
}
打印结果:
2019-04-17 18:13:23.831 24612-24612/yang.shuai.mydagger W/打印: aaa