A, GreenDao introduction
GreenDAO is an open source Android ORM ( "Object / Relational Mapping"), by ORM (referred to as "object / relational mapping"), it saves us time database development process!
By GreenDao, we can more quickly operate the database, we can use a simple object-oriented API to store, update, delete, and query Java objects.
GreenDao advantages and disadvantages?
1. High performance
2. Easy to use powerful API, covering relationships and connections
3. The minimum memory consumption
4. Library size (<100KB) constructed to hold a lower limit time and avoid Method 65k
5. Database Encryption: greenDAO support SQLCipher, to ensure the security of user data;
GreenDao core classes
GreenDao has three core classes: namely DaoMaster, DaoSession, XXXDao, three classes will be created automatically, without the need to write your own creation!
- DaoMaster :: DaoMaster database objects and manage DAO class-specific pattern. It has a static method to create a table or delete them. Its interior is class OpenHelper and DevOpenHelper SQLiteOpenHelper realize that they create patterns in the SQLite database.
- DaoSession: All available DAO object management specific pattern, you can use one getter method to get the object. DaoSession also provides some general persistence methods, such as the entity is inserted, load, update, delete and refresh.
- XXXDao: Data Access Objects (DAO) and persistent query entity. For each entity, greenDAO generated DAO. It has more than DaoSession persistence method.
- Entities: be persistent object. Typically, the database entity object representative of a line using the standard Java properties (e.g., a POJO or JavaBean).
Two, GreenDao use
1. Import Gradle widget code generation and Dao
To use GreenDao in the Android project, you need to add plug-ins and add GreenDao GreenDao Gradle library:
a). Import widget
// 在 Project的build.gradle 文件中添加: buildscript { repositories { jcenter() mavenCentral() // add repository } dependencies { classpath 'com.android.tools.build:gradle:3.1.2' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin } }
b). configure its dependencies
// 在 Moudle:app的 build.gradle 文件中添加: apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao' // apply plugin dependencies { implementation 'org.greenrobot:greendao:3.2.2' // add library }
c). the configuration database information
{greendao schemaVersion . 1 // database version number daoPackage 'com.renhui.testapp.functions.database.greenDao.db' // set DaoMaster, DaoSession, Dao package names targetGenDir 'src.main.java' // set DaoMaster, DaoSession, Dao directory, note that with this path. Do not use / generateTests to false // set true to automatically generate test unit. targetGenDirTests 'the src / main / Java' // should be stored substantially catalog generation unit tests. The default is src / androidTest / java. }
Configuration is complete, use Build> Make Project In Android Studio, rewrite build the project, GreenDao the integration is complete!
2. Create a storage object entity classes
GreenDao using only data stored in the storing annotation data previously declared class @Entity let GreenDao for generating the necessary code:
@Entity public class Student { the @Id (AUTOINCREMENT = to true ) Long the above mentioned id; @Unique int studentNo; // Student ID int Age; // Age String Cellphone; // phone number String Sex; // gender String name; // Name address String; // home address String schoolName; // school name String grade; // What grade ...... getter and setter and constructor Method, ...... }
3. GreenDao initialization
We can maintain a global conversation in the Application. We initialize the database operations in Applicaiton: =
/** * 初始化GreenDao,直接在Application中进行初始化操作 */ private void initGreenDao() { DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "aserbao.db"); SQLiteDatabase db = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(db); daoSession = daoMaster.newSession(); } private DaoSession daoSession; public DaoSession getDaoSession() { return daoSession; }
After initialization is complete again rebuild what the project will find a set of directories targetGenDir generate three types of documents, this is GreenDao generated automatically! Description of the database has been connected, we just need to be followed by additions and deletions to change search the database operation on the line.
4. GreenDao implemented CRUD
1. increase
insert () Insert data
@Override public void insertData(Thing s) { DaoSession daoSession = ((AserbaoApplication) getApplication()).getDaoSession(); for (int i = 0; i < 1000; i++) { Student student = new Student(); student.setStudentNo(i); int age = mRandom.nextInt(10) + 10; student.setAge(age); student.setTelPhone(RandomValue.getTel()); String chineseName = RandomValue.getChineseName(); student.setName(chineseName); if (i % 2 == 0) { student.setSex("男"); } else { student.setSex("女"); } student.setAddress(RandomValue.getRoad()); student.setGrade(String.valueOf(age % 10) + "年纪"); student.setSchoolName(RandomValue.getSchoolName()); daoSession.insert(student); } }
insertOrReplace () data exists is replaced, the data does not exist insert
@Override public void insertData(Thing s) { DaoSession daoSession = ((AserbaoApplication) getApplication()).getDaoSession(); for (int i = 0; i < 1000; i++) { Student student = new Student(); student.setStudentNo(i); int age = mRandom.nextInt(10) + 10; student.setAge(age); student.setTelPhone(RandomValue.getTel()); String chineseName = RandomValue.getChineseName(); student.setName(chineseName); if (i % 2 == 0) { student.setSex ( "M" ); } the else { student.setSex ( "F" ); } student.setAddress (RandomValue.getRoad ()); student.setGrade (String.valueOf (Age % 10) + "old" ) ; student.setSchoolName (RandomValue.getSchoolName ()); daoSession.insertOrReplace (Student); // insert or replace } }
2. deleted
There are two ways to delete: delete () and deleteAll (); respectively, and delete all delete individual.
@Override public void deleteData(Student s) { DaoSession daoSession = ((AserbaoApplication) getApplication()).getDaoSession(); daoSession.delete(s); } @Override public void deleteAll() { DaoSession daoSession = ((AserbaoApplication) getApplication()).getDaoSession(); daoSession.deleteAll(Student.class); }
3. change
Be modified by the update:
@Override public void updataData(Student s) { DaoSession daoSession = ((AserbaoApplication) getApplication()).getDaoSession(); daoSession.update(s); }
4. Charles
The method of inquiry are:
- loadAll (): Query all data.
- queryRaw (): according to the conditions query.
- queryBuilder (): easily create queries, followed by a detailed explanation.
public List queryAll() { List<Student> students = daoSession.loadAll(Student.class); return students; } @Override public void queryData(String s) { List<Student> students = daoSession.queryRaw(Student.class, " where id = ?", s); mDataBaseAdapter.addNewStudentData(students); }
Reference: https://www.jianshu.com/p/53083f782ea2