I re-wrote greenDAO in Android Studio to understand how to configure and operate greenDAO and the coding process under AS.

configuration

GreenDAO uses the principle that you need to build a Java project to generate related beans, similar to Hibernate; The principle is object-relational Mapping (ORM), which means a Mapping between Relational databases and objects. Objects and relationships can map each other. When operating database tables, you do not need to write complex SQL statements and directly operate objects. GreenDAO is the process of persisting an object, mapping table fields to in-memory object attributes.

In Eclipse, you can create a Java project directly, whereas in AS, you need to create a Java Module.

  • Create a New module in your Android project (Click File > New Module. Select Java Library and Click Next)
  • Input the package name, etc and click Finish
  • Configure greenDAO’s lib in the generated Module build file
  • Click on the Run menu to see the following, indicating that the configuration is successful.

use

  • Design the related bean files and convert them into the entity classes containing the corresponding fields according to your own database table design.
Entity company = schema.addEntity("Company"); company.addIdProperty().autoincrement(); / / on the company. AddDateProperty (" regTime ");Copy the code

AddXXXProperty (); addXXXProperty(); addXXXProperty(); Of course, your table may be very complex, involving multiple primary keys associated with the table foreign key, GreenDAO provides related methods to set; A company corresponds to multiple employees, and a 1 is formed between the company and employee tables. N multiple relationships: The employee bean holds the primary key(comId) of a company

Property logid = logItem.addLongProperty("comId").getProperty();
logItem.addToOne(company, logid);
ToMany loglist = company.addToMany(logItem, logid);
loglist.setName("staffList");
Copy the code
  • generate

The key to generating beans

Schema schema = new Schema(1, "package.name"); //param[0] new DaoGenerator(). GenerateAll (schema,"your file path"); // Param [0] new DaoGenerator(). // Set the generated file to the package in your projectCopy the code

Note that when your table structure changes, you need to update the version number of the parameters in the Schema class accordingly.

  • The CRUD of a database, such as adding staff code, is relatively straightforward to handle

    staffDao.insert(Staff); staffDao.insertInTx(staffList); // If you want to batch insertCopy the code

    Query (batch query)

    QueryBuilder<Staff> qb = staffDao.queryBuilder(); qb.orderDesc(Properties.Id); / / reverseCopy the code

    delete

    staffDao.delete(staff); ID QueryBuilder<Staff> qb = staffdao.queryBuilder (); DeleteQuery<Staff> dq = qb.where(Properties.id.eq(no)).buildDelete();Copy the code