前言
Greendao是一款用于数据库创建与管理的框架,由于原生SQLite语言比较复杂繁琐,使得不少程序员不得不去学习SQLite原生语言,但是学习成本高,效率低下,所以不少公司致力于开发一款简单的数据库管理框架,较为著名的就有Greendao和ORMLite,但是就数据分析来看,Greendao的效率是高于ORMLite及其他框架的,是目前该行业的领先者。也因为Greendao的使用方法简便,且效率高使得其成为目前使用最为广泛的数据库管理框架。
优点
1:存取速度快。
2:支持数据库加密
3:轻量级
4:支持缓存
5:自动生成代码
第一步,环境配置
在build.gradle文件下添加如下代码
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
这是在gradle的具体位置
buildscript {
repositories {
google()
jcenter()
maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.0-alpha01'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' //添加的是这一句
}
}
App的build.gradle的配置如下
apply plugin: 'org.greenrobot.greendao' // apply plugin
greendao {
schemaVersion 1 //数据库版本
targetGenDir 'src/main/java' //指定生成代码的目录
daoPackage //生成代码到具体包下
}
implementation 'org.greenrobot:greendao:3.2.2' // add library
这是App的gradle配置
第二部,新建一个实体类加上@Entity注解,代码如下
@Entity(nameInDb = "STUDENT")//数据库的名字
public class StudentDao {
@Id(autoincrement = true)//主键自增,,传入对象时不需要传入
@Unique//保证该值在表单中的唯一性
private Long id;
@Property(nameInDb = "name")
private String name;//名字
@Property(nameInDb = "mark")
private String mark;
@Generated(hash = 1600034907)
public StudentDao(Long id, String name, String mark) {
this.id = id;
this.name = name;
this.mark = mark;
}
@Generated(hash = 85746134)
public StudentDao() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getMark() {
return this.mark;
}
public void setMark(String mark) {
this.mark = mark;
}
}
@Entity:告诉GreenDao该对象为实体,只有被@Entity注释的Bean类才能被dao类操作
@Id:对象的Id,使用Long类型作为EntityId,否则会报错。(autoincrement = true)表示主键会自增,如果false就会使用旧值
@Property:可以自定义字段名,注意外键不能使用该属性
@NotNull:属性不能为空
@Transient:使用该注释的属性不会被存入数据库的字段中
@Unique:该属性值必须在数据库中是唯一值
@Generated:编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改
第三步,做完上面这些以后点AndroidStudio的小锤子,重新构建一下,就会出现如下的类在指定路径下
接着再去https://github.com/zhanghangcode/MigrationHelper这个网址复制两个类粘贴在你的项目中
自己创建两个类,分别是DbManager数据库的管理类和DbHelper数据库的方法调用类,直接上代码吧,
DbManager代码如下
public class DbManager {
private static final String DATABASE_NAME="student_data";
private static DbManager instance;
private DaoSession daoSession;
private DaoMaster.DevOpenHelper devOpenHelper;
private DaoMaster daoMaster;
public static DbManager getInstance(){
if(instance==null){
synchronized (DbManager.class){
if(instance==null){
instance=new DbManager();
}
}
}
return instance;
}
public void initDb(Context context){
devOpenHelper= new DaoMaster.DevOpenHelper(context,DATABASE_NAME,null);
daoMaster=new DaoMaster(devOpenHelper.getWritableDatabase());
daoSession=daoMaster.newSession();
Log.i("TAG", "initDb: 打开了数据库");
}
public DaoSession getDaoSession(){
return daoSession;
}
public void closeDataBase(){
if(devOpenHelper!=null){
Log.i("TAG", "closeDataBase:关闭数据库 ");
}
closeHelper();
closeDaoSession();
}
private void closeHelper() {
if(devOpenHelper!=null){
devOpenHelper.close();
devOpenHelper=null;
}
}
private void closeDaoSession() {
if(daoSession!=null){
daoSession.clear();
daoSession=null;
}
}
}
DbHelper代码如下
public class DbHelper {
//插入数据的方法
public static boolean insertStudentInfo(StudentDao studentDao){
if(studentDao==null){
return false;
}else {
StudentDaoDao studentDaoDao = DbManager.getInstance().getDaoSession().getStudentDaoDao();
long index = studentDaoDao.insertOrReplace(studentDao);
Log.i("TAG", "insertStudentInfo: "+index);
return true;
}
}
//查询数据库所有数据
public static List queryAllStudent(){
StudentDaoDao studentDaoDao = DbManager.getInstance().getDaoSession().getStudentDaoDao();
return studentDaoDao.loadAll();
}
//删除数据库某条数据,根据ID删除
public static boolean delet_studentdao(Long key){
if(key==null){
return false;
}else {
StudentDaoDao studentDaoDao = DbManager.getInstance().getDaoSession().getStudentDaoDao();
studentDaoDao.deleteByKey(key);
Log.i("TAG", "delet_studentdao: 删除 "+key);
return true;
}
}
//更新某条数据,根据id更新
public static boolean updata_studentdao(StudentDao studentDao){
if(studentDao==null){
return false;
}else {
StudentDaoDao studentDaoDao = DbManager.getInstance().getDaoSession().getStudentDaoDao();
studentDaoDao.update(studentDao);
return true;
}
}
}
对了,做完这些不要忘了在Application里初始化DbManager管理类
DbManager.getInstance().initDb(this);
在Activity的代码如下
public class MainActivity extends AppCompatActivity {
private EditText nameEdit;
private EditText pwdEdit;
private Button insertButton;
private Button selectallButton;
private Button deleteButton;
private Button updataButton;
private EditText updataEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updataButton = (Button) findViewById(R.id.updata_button);
updataButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updata_student();
}
});
deleteButton = (Button) findViewById(R.id.delete_button);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
delete_one();
}
});
updataEdit = (EditText) findViewById(R.id.updata_edit);
nameEdit = (EditText) findViewById(R.id.name_edit);
pwdEdit = (EditText) findViewById(R.id.pwd_edit);
insertButton = (Button) findViewById(R.id.insert_button);
selectallButton = (Button) findViewById(R.id.selectall_button);
insertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
save();
}
});
selectallButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
queryAll();
}
});
}
private void save(){
StudentDao studentDao=new StudentDao();
studentDao.setName(nameEdit.getText().toString().trim());
studentDao.setMark(pwdEdit.getText().toString().trim());
boolean b = DbHelper.insertStudentInfo(studentDao);
Log.i("TAG", "save: "+b);
}
private void queryAll(){
List studentList = DbHelper.queryAllStudent();
if (studentList == null) {
Log.i("TAG", "queryAll: 没有数据");
return;
}
for (int i = 0; i < studentList.size(); i++) {
Log.i("TAG", "queryAll: ID:"+studentList.get(i).getId()+"Name:"+studentList.get(i).getName()+"Pwd"+studentList.get(i).getMark());
}
}
private void delete_one(){
String trim = nameEdit.getText().toString().trim();
Long aLong = Long.valueOf(trim);
boolean b = DbHelper.delet_studentdao(aLong);
Log.i("TAG", "delete_one: "+b);
}
private void updata_student(){
StudentDao studentDao=new StudentDao();
String trim = updataEdit.getText().toString().trim();
Long aLong = Long.valueOf(trim);
if(aLong==null){
Toast.makeText(this, "还没输入更新第几个数据", Toast.LENGTH_SHORT).show();
return;
}else {
studentDao.setId(aLong);
studentDao.setName(nameEdit.getText().toString().trim());
studentDao.setMark(pwdEdit.getText().toString().trim());
boolean b = DbHelper.updata_studentdao(studentDao);
Log.i("TAG", "updata_student: "+b);
}
}
到这里GreenDao基本的数据库增删改查已经做完了,下期再见