GreenDao learning for Android ORM

Source: Internet
Author: User
Tags maven central

GreenDao learning for Android ORM
 

GreenDao is a high-performance ORM framework in Android. (Others include OrmLite)
 

At the same time, GreenDao has a sub-project named GreenDao Code Generator:

The GreenDao core class and its work are as follows:

Use Initialization

Use greendao to add greendao. jar;
(Using greendao-generator requires the addition of greendao-generator.jar and freemarker. jar, which will be discussed later)
Jar packages can be downloaded from the maven central repository.

Helper = new DaoMaster. devOpenHelper (this, notes-db, null); // greendao creates the notes-db database db = helper. getWritableDatabase (); daoMaster = new DaoMaster (db); daoSession = daoMaster. newSession (); noteDao = daoSession. getNoteDao (); example: [java] view plaincopyNote note = new Note (null, noteText, comment, new Date (); noteDao. insert (note); Log. d (DaoExample, Inserted new note, ID: + note. getId (); [java] view plaincopynoteDao. deleteByKey (id );
Data Model and code generation

Complete example:

GenConfig. java
Import java. io. IOException; import de. greenrobot. daogenerator. *; public class GenConfig {public static void main (String [] args) throws IOException, Exception {Schema schema = new Schema (1, net. xby1993.baiduttstest); Entity note = schema. addEntity (RSSModel); note. addIdProperty (). primaryKey (). autoincrement (); note. addStringProperty (title ). notNull (); note. addStringProperty (url); note. addDateProperty (date); note. addStringProperty (summary); note. addStringProperty (encoding); new DaoGenerator (). generateAll (schema, D:/lucene/src); // ensure that the directory must exist; otherwise, an error is returned }}

Generally, you need to create two projects to use GreeDao. One is to add greendao to your Android project. jar dependency. The other is a common java se project. add greendao-generator.jar and freemarker. jar dependency. The latter is used to generate data model domain, dao, DaoMaster and other code.
The DoMaster, DaoSession, XxxDao, and entity classes are generated. DoMaster and DaoSession correspond to your current data model. The methods for generating each data model in these two classes are different.
Data Model Code Generation example-use greendao-generator:

GenConfig. java
Schema schema = new Schema(1, de.greenrobot.daoexample);   Entity note= schema.addEntity(Note);  note.addIdProperty();  note.addStringProperty(text).notNull();  note.addStringProperty(comment);  note.addDateProperty(date);   new DaoGenerator().generateAll(schema, ../DaoExample/src-gen);  

Schema indicates your database, and Entity indicates the structure of the data table to be generated. Adding a property to Entity is equivalent to adding a column structure.

 

Note: The ../DaoExample/src-gen path must exist. Otherwise, an error is returned.

 

 

Modeled entity Entities

Schema:
Schema schema = new Schema (1, de. greenrobot. daoexample); // The first parameter represents the version, and the second parameter represents the package name of the Code to be generated. By default, the Dao class and the Test class are in the same package. If you want to separate them, you can do this: schema. setdefajavjavapackagetest (de. greenrobot. daoexample. test); schema. setdefajavjavapackagedao (de. greenrobot. daoexample. dao); Schema has two default Flags for Entity: schema2.enableKeepSectionsByDefault (); schema2.enableActiveEntitiesByDefault ();
Entity

Schema can be used to add Entity:
Entity user = schema. addEntity ("User ");
Add attributes to an object:
User. addIdProperty ();
User. addStringProperty ("name ");
User. addStringProperty ("password ");
User. addIntProperty ("yearOfBirth ");

Add a primary key to an object

Note: The primary key support of greendao is not complete yet and is still under development. However, you can use the following method to add a primary key:

user.addIdProperty().primaryKey().autoIncrement();  
Rules and differences between naming Java attributes and corresponding database table names

Attributes in Java generally use the hump naming method.
You can use Entity. setTableName to modify the table name.

Table Name/domain Class Name Attribute/column I  
Java User Name
Database USER NAME
Inheritance, Interfaces, and Serializable

For inheritance: (not recommended)
MyEntity. setSuperclass ("MyCommonBehavior ");
We recommend that you use interfaces to extract some common attributes.
EntityA. implementsInterface ("C ");
EntityB. implementsInterface ("C ");
EntityB. implementsSerializable ();

Trigger code generation

DaoGenerator daoGenerator = new DaoGenerator ();
DaoGenerator. generateAll (schema, "../MyProject/src-gen ");
You can also specify the third parameter to separate the test code.

Keep sections Fragment

Since GreenDaoGenerator will overwrite the original entity code after each run, in order to allow add troops to keep your custom code to your entity, greendao uses "keep sections" to allow you to add, but you must first call the Schema's enableKeepSectionsByDefault () or setHasKeepSections (true ). after running generator, the following comments will be generated in the generated entity class. We only need to add custom code to these comments, and the code will be retained after each running of generator.

// KEEP INCLUDES - put your custom includes here  // KEEP INCLUDES END  ...  // KEEP FIELDS - put your custom fields here  // KEEP FIELDS END  ...  // KEEP METHODS - put your custom methods here  // KEEP METHODS END  

 

 

Do not delete these comments.

 

 

SessionsDaoMaster and DaoSession
daoMaster = new DaoMaster(db);  daoSession = daoMaster.newSession();  noteDao = daoSession.getNoteDao();  

Note that the database connection belongs to the DaoMaster, and the memory needs to be allocated for each Session. For entities, greendao uses the corresponding session cache.

Identity scope and session "cache"

By default, greendao returns the same java objects for multiple different queries. For example, if an object with ID 42 is loaded from the USER table, the same java object is returned for each query.
Another function is to cache entities. Greendao uses weak reference to store objects in the memory. Therefore, when it is loaded again, greendao does not load objects from the database, but directly returns objects in the session cache.

 

Note: Once you need to change it, you can submit it to the database in time, but the object data in the cache is still not updated. In this case, you need to manually update the objects in the cache. Remember !!!

 

 

Multi-Table relationship ing To-One

It is equivalent to a foreign key relationship.

// The variables user and picture are just regular entities  Property pictureIdProperty = user.addLongProperty(pictureId).getProperty();  user.addToOne(picture, pictureIdProperty);  

This will cause the generated User entity class to have a Picture attribute (getPicture/setPicture );

Relation Names and multiple Relations

Each association has a name. By default, the associated name is the name of the target object. Therefore, we recommend that you manually set the name of the association to avoid duplicate names. You can set it through setName.

Property pictureIdProperty = user. addLongProperty (pictureId ). getProperty (); Property thumbnailIdProperty = user. addLongProperty (thumbnailId ). getProperty (); user. addToOne (picture, pictureIdProperty); // use the default Link name user. addToOne (picture, thumbnailIdProperty, thumbnail); // to prevent duplicate names, set the Link name to thumbnail Property customerId = order. addLongProperty (customerId ). notNull (). getProperty (); tow.customertoorders = customer. addtoorders (order, customerId); customerToOrders. setName (orders); // Optional customerToOrders. orderAsc (orderDate); // In the code generated by Optional, the Customer class will have one more getOrders () List orders = customer. getOrders ();
Resolving and Updating To-related Relations

For the first time, To-resolve is used for lazy loading. However, once loaded, the to-resolve list will be cached in a List, and subsequent requests will not go through the database, instead, the data is directly returned from the cache. Therefore, after modification, you must update the data in the cache.
The following code may produce confusing results due to Caching:

List orders1 = customer.getOrders();  int size1 = orders1.size();   Order order = new Order();  order.setCustomerId(customer.getId());  daoSession.insert(order);   Listorders2 = customer.getOrders();  // size1 == orders2.size(); // NOT updated  // orders1 == orders2; // SAME list object  

Therefore, we need to update the cache.
The corrected code is as follows:

List orders = customer. getOrders (); newOrder. setCustomerId (customer. getId (); daoSession. insert (newOrder); orders. add (newOrder); // update the cache also applies to delete operations. : List orders = customer. getOrders (); daoSession. delete (newOrder); orders. remove (newOrder); // update Cache

However, if you cannot meet your expectation or it is difficult to update the cache, greendao also provides the following resetXxx () method to reset the cache:

customer.resetOrders();  List orders2 = customer.getOrders();  
Bidirectional Association To-One and To-pair
Entity customer = schema. addEntity (Customer); customer. addIdProperty (); customer. addStringProperty (name ). notNull (); Entity order = schema. addEntity (Order); order. setTableName (ORDERS); // ORDER is a reserved keyword order. addIdProperty (); Property orderDate = order. addDateProperty (date ). getProperty (); Property customerId = order. addLongProperty (customerId ). notNull (). getProperty (); order. addToOne (cuz Tomer, customerId); tow.customertoorders = customer. addtoorders (order, customerId); customerToOrders. setName (orders); customerToOrders. orderAsc (orderDate); this produces a bidirectional Association. List allOrdersOfCustomer = order. getCustomer (). getOrders ();
Relational-to-relational Relations (n: m)

 

 

Currently, greendao has not been implemented.

 

 

Modelling Tree Relations

You can model a tree relation by modelling an entity having a to-one and a to-between relation pointing to itself:

Entity treeEntity = schema. addEntity (TreeEntity); treeEntity. addIdProperty (); Property parentIdProperty = treeEntity. addLongProperty (parentId ). getProperty (); treeEntity. addToOne (treeEntity, parentIdProperty ). setName (parent); treeEntity. addtoty (treeEntity, parentIdProperty ). setName (children); then we can navigate to the generated code: [java] view plaincopyTreeEntity parent = child. getParent (); List grandChildren = child. getChildren ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.