使用:
1、在build.gradle中添加
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() mavenCentral() // add repository GreenDao } dependencies { classpath "com.android.tools.build:gradle:4.1.3" classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0' // add plugin GreenDao // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
2、在app包的build.gradle中
plugins { id 'com.android.application' id 'org.greenrobot.greendao' // apply plugin } android { compileSdkVersion 30 buildToolsVersion "30.0.3" defaultConfig { applicationId "com.example.mygreendao" minSdkVersion 16 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } greendao { //数据库的schema版本,也可以理解为数据库版本号 schemaVersion 1 //设置DaoMaster、DaoSession、Dao包名,也就是要放置这些类的包的全路径。 daoPackage 'com.example.mygreendao.greendao' //设置DaoMaster、DaoSession、Dao目录 targetGenDir 'src/main/java' } } dependencies { implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'com.google.android.material:material:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' //GreenDao implementation 'org.greenrobot:greendao:3.3.0' // add library }
项目内容如下图:
3、创建Student实体类
package com.example.mygreendao.bean; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Generated; @Entity public class Student { @Id(autoincrement = true)//自增ID private Long id; private String name; private int age; //有参构造 @Generated(hash = 352757281) public Student(Long id, String name, int age) { this.id = id; this.name = name; this.age = age; } //无参构造 @Generated(hash = 1556870573) public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } 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 int getAge() { return this.age; } public void setAge(int age) { this.age = age; } }
4、修复一下工程,自动生成greendao包下的类(就是点击一下小锤子),你会自动生成上图中greendao包中的类。
5、开始使用,创建管理类
package com.example.mygreendao.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.example.mygreendao.greendao.DaoMaster; import com.example.mygreendao.greendao.DaoSession; public class DbManager { //数据库名称 private static final String DB_NAME = "test.db"; private Context mContext;//上下文 private static DbManager mDbManager; private static DaoMaster.DevOpenHelper mDevOpenHelper; private static DaoMaster mDaoMaster; private static DaoSession mDaoSession; private DbManager(Context context){ this.mContext = context; // 初始化数据库信息 mDevOpenHelper = new DaoMaster.DevOpenHelper(context,DB_NAME); getDaoMaster(context); getDaoSession(context); } public static DbManager getInstance(Context context){ if (null == mDbManager){ synchronized (DbManager.class){ if (null == mDbManager){ mDbManager = new DbManager(context); } } } return mDbManager; } /** * 获取可读数据库 * @param context * @return */ public static SQLiteDatabase getReadableDatabase(Context context){ if (null == mDevOpenHelper){ getInstance(context); } return mDevOpenHelper.getReadableDatabase(); } /** * 获取可写数据库 * @param context * @return */ public static SQLiteDatabase getWritableDatabase(Context context) { if (null == mDevOpenHelper) { getInstance(context); } return mDevOpenHelper.getWritableDatabase(); } /** * 获取DaoMaster * @param context * @return */ public static DaoMaster getDaoMaster(Context context){ if (null == mDaoMaster){ synchronized (DbManager.class){ if (null == mDaoMaster){ mDaoMaster = new DaoMaster(getWritableDatabase(context)); } } } return mDaoMaster; } /** * 获取DaoSession * @param context * @return */ public static DaoSession getDaoSession(Context context) { if (null == mDaoSession) { synchronized (DbManager.class) { mDaoSession = getDaoMaster(context).newSession(); } } return mDaoSession; } }
6、增删改查
package com.example.mygreendao.db; import android.content.Context; import com.example.mygreendao.bean.Student; import com.example.mygreendao.greendao.StudentDao; import org.greenrobot.greendao.query.QueryBuilder; import java.util.List; public class StudentDaoOpen { /** * 添加数据至数据库 * @param context * @param student */ public static void insertData(Context context, Student student){ DbManager.getDaoSession(context).getStudentDao().insert(student); } /** * 将数据实体通过事务添加至数据库 * @param context * @param list */ public static void inserData(Context context, List<Student> list){ if (null == list || list.size() <= 0) { return; } DbManager.getDaoSession(context).getStudentDao().insertInTx(list); } /** * 添加数据至数据库,如果存在,将原来的数据覆盖 * 内部代码判断了如果存在就update(entity);不存在就insert(entity); * @param context * @param student */ public static void saveData(Context context, Student student) { DbManager.getDaoSession(context).getStudentDao().save(student); } /** * 删除数据至数据库 * @param context * @param student 删除具体内容 */ public static void deleteData(Context context, Student student) { DbManager.getDaoSession(context).getStudentDao().delete(student); } /** * 根据id删除数据至数据库 * @param context * @param id 删除具体内容 */ public static void deleteByKeyData(Context context, long id) { DbManager.getDaoSession(context).getStudentDao().deleteByKey(id); } /** * 删除全部数据 * @param context */ public static void deleteAllData(Context context) { DbManager.getDaoSession(context).getStudentDao().deleteAll(); } /** * 更新数据库 * * @param context * @param student */ public static void updateData(Context context, Student student) { DbManager.getDaoSession(context).getStudentDao().update(student); } /** * 查询所有数据 * @param context * @return */ public static List<Student> queryAll(Context context) { QueryBuilder<Student> builder = DbManager.getDaoSession(context).getStudentDao().queryBuilder(); return builder.build().list(); } /** * 根据id,其他的字段类似 * @param context * @param id * @return */ public static List<Student> queryForId(Context context, long id) { QueryBuilder<Student> builder = DbManager.getDaoSession(context).getStudentDao().queryBuilder(); /** * 返回当前id的数据集合,当然where(这里面可以有多组,做为条件); * 这里build.list();与where(StudentDao.Properties.Id.eq(id)).list()结果是一样的; * 在QueryBuilder类中list()方法return build().list(); */ // Query<Student> build = builder.where(StudentDao.Properties.Id.eq(id)).build(); // List<Student> list = build.list(); return builder.where(StudentDao.Properties.Id.eq(id)).list(); } }
7、布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/add" android:layout_width="match_parent" android:layout_height="40dp" android:text="增" /> <Button android:id="@+id/delete" android:layout_width="match_parent" android:layout_height="40dp" android:text="删" /> <Button android:id="@+id/updata" android:layout_width="match_parent" android:layout_height="40dp" android:text="改" /> <Button android:id="@+id/check" android:layout_width="match_parent" android:layout_height="40dp" android:text="查" /> <Button android:id="@+id/deleteAll" android:layout_width="match_parent" android:layout_height="40dp" android:text="删除全部" /> <Button android:id="@+id/check_id" android:layout_width="match_parent" android:layout_height="40dp" android:text="根据id查" /> </LinearLayout>
8、调用
package com.example.mygreendao; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import com.example.mygreendao.bean.Student; import com.example.mygreendao.db.StudentDaoOpen; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Context mContext; private Button add; private Button delete; private Button updata; private Button check; private Button deleteAll; private Button check_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; add = findViewById(R.id.add); add.setOnClickListener(this); delete = findViewById(R.id.delete); delete.setOnClickListener(this); updata = findViewById(R.id.updata); updata.setOnClickListener(this); check = findViewById(R.id.check); check.setOnClickListener(this); deleteAll = findViewById(R.id.deleteAll); deleteAll.setOnClickListener(this); check_id = findViewById(R.id.check_id); check_id.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.add://添加 Student student = new Student("张三",12); StudentDaoOpen.insertData(mContext,student); Student student2 = new Student("李四",16); StudentDaoOpen.insertData(mContext,student2); Student student20 = new Student("王五",18); StudentDaoOpen.insertData(mContext,student20); break; case R.id.delete://删除 Student student3 = new Student((long)4,"张三",12); StudentDaoOpen.deleteData(mContext,student3); break; case R.id.updata://修改 Student student4 = new Student((long) 5,"李四",20); StudentDaoOpen.updateData(mContext, student4); break; case R.id.check://查询 List<Student> students = StudentDaoOpen.queryAll(mContext); for (int i = 0; i < students.size(); i++) { Log.i("Log", "Id:"+students.get(i).getId()+" ,姓名:"+students.get(i).getName()+" ,年龄:"+students.get(i).getAge()); } break; case R.id.deleteAll://删除全部 StudentDaoOpen.deleteAllData(mContext); break; case R.id.check_id://根据ID查询 List<Student> students1 = StudentDaoOpen.queryForId(mContext, 6); for (int i = 0; i < students1.size(); i++) { Log.i("Log", "Id:"+students1.get(i).getId()+" ,姓名:"+students1.get(i).getName()+" ,年龄:"+students1.get(i).getAge()); } break; } } }
结束
参考于:
https://blog.csdn.net/huangxiaoguo1/article/details/52916189
https://blog.csdn.net/bskfnvjtlyzmv867/article/details/71250101