The Greendao of Android ORM framework

Source: Internet
Author: User
Tags generator sqlite sqlite database

from:http://blog.csdn.net/kpioneer123/article/details/51354436

Greendao is an object/relational mapping (ORM) tool for Android development. It provides an object-oriented interface to the SQLite database. ORM tools like Greendao not only save you a lot of repetitive work, but also provide a simpler interface to operate. Greendao code-generated engineering structure diagram



The main goal of Greendao design

A streamlined library

Maximize performance

Minimized memory overhead

Easy to use APIs

The main features of highly optimized Greendao design for Android

Greendao performance is much higher than that of similar ormlite.

Greendao supports direct storage of protocol buffer (PROTOBUF) protocol data, and if you interact with the server through the PROTOBUF protocol, no mapping is required.

Unlike ORM frameworks, such as ormlite, which use annotations, Greendao uses "code generation", which is why performance can increase dramatically. DAO CODE GENERATION PROJECT

This is the core concept: in order to use Greendao in our Android project, we need to build another pure Java project to automatically generate the beans, DAO, daomaster, daosession that need to be used in subsequent Android projects and other classes.

To use Greendao in your Android project, you need to create a level two project: "Generator Project", which is the task of generating specific code for your domain. This builder project is an ordinary Java project. Ensure that the Greendao Greendao-generator.jar and Freemarker.jar are in classpath. Create an executable Java class, build your entity model and trigger the code generator, and see the modelling documentation for more details.

Core Class

Once you have generated the specified code, you can use Greendao in your Android project. Don't forget to introduce Greendao's core jar package to your Android project: Greendao.jar. The following are some of the necessary interfaces for Greendao.


Daomaster:

Daomaster holds database Objects (sqlitedatabase) in a certain pattern and manages some DAO classes (not objects).

There is a static method to create and drop database tables. Its internal classes Openhelper and Devopenhelper are sqliteopenhelper implementation classes that create patterns for SQLite databases.


Daosession:

Manages all the available DAO objects in the specified mode, which you can obtain by using a GET method. Daosession provides some common methods of persistence, such as inserting, loading, updating, refreshing, and deleting entities. The final Daosession object will track the identity scope, more details, and refer to the session documentation.


DAOs (Data Access Objects):

Data access objects for persistence and querying of entities. For each entity, Greendao generates a DAO, which has more persistent methods than daosession, such as loading all, inserting (INSERTINTX, the context is not clear, the short translation into the insertion).

Specific steps to operate:

STEP1: Configure the "greendao generator" module in the ANDROID project

1. In the. Src/main directory, create a new "java-gen" directory with Java at the same level, which is used to store classes of beans, DAO, daomaster, daosession, etc. generated by Greendao.

New->directory (Mingjava-gen)


2. Configure the Android Engineering (APP) Build.gradle to add sourcesets and dependencies to the android{} structure.

[Java]View Plain copy sourcesets {main {java.srcdirs = [' Src/main/java ', ' Src/main/java-gen ']} } Compile ' org.greenrobot:greendao:2.2.0 '
STEP2:New "greendao generator" Module (Pure JAVA Engineering)1. Through the File-> new-> new Module-> Java Library-> Fill in the appropriate package name and class name-> Finish.


The module structure generated in this way (I named Greendao_generator) is different from the general situation
2. Configure the Build.gradle of Greendao_generator project, add dependencies. [Java]View plain copy compile ' org.greenrobot:greendao-generator:2.2.0 '
3. Write MyClass class, note: Our Java project has only one class, its content determines the output of "greendao generator", you can in this class through the object, the relationship and so on to create the database structure, I will explain in detail the code content in the form of annotations. [Java] View plain copy package com.example;      import  de.greenrobot.daogenerator.daogenerator;   import de.greenrobot.daogenerator.entity;   import de.greenrobot.daogenerator.schema;      public class myclass{           public static void main (String[] args)   throws exception {           //  As you can see, You created a schema (schema) object to add an entity (Entity).            //  two parameters represent: the database version number and the package path that automatically generates code.            schema schema = new schema (1,   "Com.xionghu.greendao");  //       of course, if you want, you can also specify the generated  bean The directory where the   and  DAO  classes reside, as shown below:  //      schema schema  = new schema (1,  "Me.itangqi.bean");  //      schema.setdefaultjavapackagedao (" Me.itangqi.dao ");              //  Schema (schema) also has two default  flags to indicate whether  entity  is  activie  and whether to use  keep sections.            // schema2.enableactiveentitiesbydefault ();            // schema2.enablekeepsectionsbydefault ();               //  Once you have a  Schema  object, You can then use it to add an entity (entities).            addnote (Schema);               //  finally we will use the  DAOGenerator  class  generateall ()   method to generate code automatically, where you need to change the output directory (both previously created  java-gen).            //  in fact, the path of the output directory can be set in  build.gradle , interested friends can search their own, here is no longer detailed.            new daogenerator (). Generateall (schema,  " D:\\android_studio_4_6\\mygreendao\\app\\src\\main\\java-gen ");       }           /**       *  @param  schema        */       private static void  Addnote (Schema schema)  {           //  An entity (Class) is associated to a table in the database where the table is named "note" (both class name)            Entity  Note = schema.addentity ("note");           //  You can also rename the table            // note.settablename ("NODE");               // greenDAO  automatically creates a table field based on the property values of the entity class and assigns the default value             //  Next you can set the fields in the table:           note.addidproperty ();            note.addstringproperty ("text"). Notnull ();            //  The use of the hump nomenclature in  Java  is different, The name in the default database is to use uppercase and underline to separate words.            // for example, a property  called  "CreationDate"  will become a database column  "Creation_date".            note.addstringproperty ("comment");           note.adddateproperty ("date");        }     }  
STEP3: To generate a DAO file (database)Perform generator works, such as all normal, you will see the following log in the console, and in the main project "java-gen" will be found to generate Daomaster, daosession, Notedao, note a total of 4 class files. You need to configure the running conditions here. Android Studio runs Java programs

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.