The Greendao of Android_orm frame

Source: Internet
Author: User

Directory:

I. Overview

Second, download and unzip Greendao related resources

III. Application of Greendao framework

1. Create a Java project

2. Add Class Library Support

3. Create a class

Iv. Code Analysis

V. Use of Greendao

Six, the source code download

I. Overview

The storage and operation of data in Android development is not easy to avoid, this Android platform provides us with a variety of ways to store data, such as files, Sharedpreferences, SQLite and so on. Each data storage method has different characteristics, applicable to different scenarios, including SQLite application more. Although Android provides sqlitedatabase, Sqliteopenhelper help us with database operations, but in the actual development of the application is very cumbersome, then there is no more convenient and concise way to operate the SQLite database? The answer is yes, that's the ORM framework.

The ORM framework now applied to the Android platform is still much more, such as Greendao, Ormlite, Activeandroid, Sugarorm, and so on, where Greendao runs most efficiently and consumes the least memory. Let's take a look at the specific usage of Greendao.

Second, download and unzip Greendao related resources

through the official website, you can obtain Greendao related resources, official website address:http://greendao-orm.com/ .

Through the above address, the Greendao related resources download decompression, you can get six related project projects:

1, Daocore:greendao Core Library.

2, Daoexample:greendao use the sample project.

3. Daoexamplegenerator:greendao uses the example entity class and the DAO Component Builder project.

4. Daogenerator:greendao DAO Component Builder Project.

5, Daotest:greendao test project.

6. Performancetestormlite:ormlite Frame Performance test Project

III. Application of Greendao framework

After getting the resources, let's look at how to apply the Greendao framework in our Android project. Combined with official website documentation and examples, the DAO components of entities and Greendao used in Android projects need to be generated by the DAO Component Builder project. The DAO Component Builder Project creation and related code are as follows:

1. Create a Java project

  Use MyEclipse to create a common Java project with the project name: Jredu_daogenerator. Note that it is a Java project and not an Android project.

2. Add Class library support for engineering Jredu_daogenerator

  Add Class library support for engineering Jredu_daogenerator: Greendao-generator.jar and Freemarker.jar.

A) Freemaker.jar can be downloaded from this address: http://jaist.dl.sourceforge.net/project/freemarker/freemarker/2.3.21/freemarker-2.3.21.tar.gz

b) Greendao-generator.jar can be exported via Daogenerator. Just export src and src-template two directories to

3. Create class Jredudaogenerator in engineering jredu_daogenerator

Create the class Jredudaogenerator in the project Jredu_daogenerator, with the following code:

 Public Static voidMain (string[] args)throwsIOException, Exception {schema schema=NewSchema (1, "com.jredu.entity"); //entity classEntity employee = schema.addentity ("Employee"); Employee.addidproperty (); //PRIMARY KeyEmployee.addstringproperty ("name"); Employee.adddateproperty ("HireDate"); //Build    Newdaogenerator (). Generateall (Schema,"E:\\android_space\\jredu_greendao\\src"); }

Run the code that is visible in the console as a result:

Open the table of contents, we can see this project for us to generate 4 files, respectively, EmployeeDAO, Employee, Daomaster, Daosession, the content and role of the document, after the article in the introduction.

With the above steps, we are done with the generation of the entity class and the DAO component, let's analyze the classes involved in the code and their effects.

Iv. Code Analysis

schema, pattern, through source we can see some properties of this class , such as:

Private Final int version: represents the revision number of the build database.

Private Final String defaultjavapackage: Represents the default package that generates the entity class.

Private Final list<entity> Entities: holds the collection of Entity.

  So we can also think of schema as a container to hold entities.

By constructor: Schema schema = new schema (1, "com.jredu.entity"); we created a pattern, parameter 1 represents the version number of the database, and "Com.jredu.entity" represents the package for the generated Java class. It is also part of the generated class storage path.

By method: Entity employee = schema.addentity ("employee"), an entity object with the class name employee is created and added to the Entities collection property of the schema object.

  Property: A model of entity properties that is used to correlate entity properties and table columns.

  ToOne, Tomany: Used to correlate relationship mappings.

  a model of entity entities that can be used to map entity classes to corresponding tables. The main attributes are classname, tableName, attributes, indexes, relationships, etc., see the source code for details.

Schema, Entity, property, Index, ToOne, Tomany diagram:

  daogenerator: The generator of the entity class and DAO component, Generateall, according to the schema and directory parameters, first generate the file directory, and remove all entities from the schema, The corresponding entities and DAO components are generated according to the Freemaker template.

V. Use of Greendao

The related components have been generated and we will continue to describe how to use Greendao in Android projects, as follows:

1, the creation of Android project, project name: Jredu_greendao.

2. Create the package name, consistent with the package name in the schema built above. The case of this article directly builds the entity class and DAO components into this project.

3. Add Greendao jar for Jredu_greendao. Can be copied from the engineering daoexample.

4, the main code is as follows:

  Object Declaration section:

Private Daomaster Daomaster; Private daosession daosession; Private EmployeeDAO EmployeeDAO; Private Sqlitedatabase DB;

The creation part of the object:

New Daomaster.devopenhelper (thisnull);     = helper.getwritabledatabase ();     New daomaster (db);     == Daosession.getemployeedao ();

Add Features:

String name = This. Content.gettext (). toString (); if(Textutils.isempty (name)) {Toast.maketext ( This, "Please enter the employee's name! ", Toast.length_short). Show (); return; } Employee EMP=NewEmployee (NULL, Name,NewDate ()); LongEmpId =Employeedao.insert (EMP);  This. Show.settext ("New employee Number:" +empid+ "," +Emp.getid ()); //insert multiple objects at oncelist<employee> list =NewArraylist<employee>(); List.add (NewEmployee (NULL, "John Doe",NewDate ())); List.add (NewEmployee (NULL, "Harry",NewDate ())); Employeedao.insertintx (list,true); StringBuilder SB=NewStringBuilder ("Employee number after the batch has been added successfully:");  for(Employee e:list) {sb.append (E.getid ()); }      This. Show.settext ( This. Show.gettext () + "," +sb.tostring ());

Query section:

list<employee> emps=newfor(Employee e:emps) {     empstr.append ( "No.:"). Append (E.getid ()). Append (", Name:"). Append (E.getname ()). Append (", Hire date:"this.) Show.settext (Empstr.tostring ());

The end result is as follows:

From the code, we see that the implementation of the function mainly uses the employee, EmployeeDAO, Daomaster, Daosession.

Employee: Entity object, mapped to table employee.

EmployeeDAO: The code shows that this class provides methods for generating and deleting tables, and that the class inherits Abstractdao (one of the Greendao core classes, encapsulating various methods of manipulating the data in the table).

Daomaster: Inherited from Abstractdaomaster, used to create a database and manage database connections.

Daosession: Inherits from Abstractdaosession, the entry of all DAO objects, through which DAO components of the entity are obtained.

Six, the source code download

The above is the basic use of Geendao, DAO component methods, multi-table association and so on in subsequent articles continue to explain.

If in doubt, you can download the source to view the details, you can also directly comment on the consultation Oh!

The Greendao of Android_orm frame

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.