Third-party ORM framework (GreenDao) and ormgreendao for Android development databases
The user experience is very important when mobile apps are pursuing functions. When you start an APP, you must change the developer role at any time.
Standing in the APP development role and in the producer position; when you test, you should put yourself in the user role to consider the APP you have made. For example
For example, we use news and friend dynamics on mobile phones every day. When you do not have a network, there are also data to provide users with browsing, rather than a "White Paper ".
The computer crashes. This is the last data cache in the Network State provided by the mobile APP during development.
Storage cache and hardware cache. Here I mainly talk about a hardware cache-a third-party ORM framework (GreenDao) for Android development databases ).
Mobile apps that have been developed for so long have a relatively small amount of work recently and are idle to optimize the performance of development projects. Because the project involves a lot of cache processing and data
Database usage requires frequent read/write and query operations on the database. Therefore, we first thought of optimizing the database framework of the entire project. Android itself was used
The built-in sqllite is the most basic SQLiteOpenHelper method, which is easy to understand. However, it is very tedious to use,
From table creation to addition, deletion, modification, and query of tables, if the table object has many attributes, a large amount of code is required for table creation and insertion. The logarithm is also required in code execution.
Close the database and cursor in time (enable and disable when used up), and some SQL languages are required, which is especially inconvenient for debugging when Bugs are generated during development. Currently
Typical orm frameworks for android include greenDAO, OrmLite, and AndrORM. Based on various online evaluations, greenDAO has the highest operating efficiency and the most memory consumption.
Low, the best performance. Therefore, we decided to adopt the greenDAO framework to improve the project's orm framework.
How can we express the advantages of greenDAO? The following comparison of greenDAO and ORMLite performance:
After several days of modification, the database related to the project is finally optimized. In this process, it is found that greenDAO has good performance and is quite convenient to use. It does not need to involve any SQL language. You can directly create tables, add, delete, modify, and query through object classes, especially api interfaces are easy to understand. I found that there were too few learning materials in China during my study, so I decided to record my experiences and methods on using this orm framework.
I. greenDAO framework resources
First, as a third-party database ORM framework, greenDAO must have resources such as related websites.
1, greenDAO Official Website: http://greendao-orm.com/
2. Project: https://github.com/greenrobot/greenDAO (or official website)
GreenDAO Is An ORM solution that helps Android Developers quickly map Java objects to SQLite database forms. by using a simple object-oriented API, developers can store, update, delete, and query Java objects.
GreenDAO's main design goals:
* Maximum performance (the fastest Android ORM)
* Easy-to-use APIs
* Highly optimized
* Minimum memory consumption
Ii. Development and usage steps (key points)
1. Download The greenDAO framework resources, decompress and analyze the official Demo, which contains six project directories:
(1). DaoCore: Library directory, that is, the code of the jar file greendao-1.3.0-beta-1.jar;
(2). DaoExample: android sample project;
(3). DaoExampleGenerator: DaoExample project's DAO class constructor, java project;
(4). DaoGenerator: DAO class constructor, java project;
(5). DaoTest and PerformanceTestOrmLite: other test-related projects.
2. DAO class construction
First you need to create a new java project to generate the DAO class file, the project needs to import greendao-generator.jar and freemarker. jar file to the project.
Public class ExampleDaoGenerator
{
Public static void main (String [] args) throws Exception
{
Schema schema = new Schema (3, "de. greenrobot. daoexample ");
AddNote (schema );
AddCustomerOrder (schema );
New DaoGenerator (). generateAll (schema, "../DaoExample/src-gen ");
}
Private static void addNote (Schema schema)
{
Entity note = schema. addEntity ("Note ");
Note. addIdProperty ();
Note. addStringProperty ("text"). notNull ();
Note. addStringProperty ("comment ");
Note. addDateProperty ("date ");
}
Private static void addCustomerOrder (Schema schema)
{
Entity customer = schema. addEntity ("Customer ");
Customer. addIdProperty ();
Customer. addStringProperty ("name"). notNull ();
Entity order = schema. addEntity ("Order ");
Order. setTableName ("ORDERS"); // "ORDER" is a reserved key <a href = "http://www.it165.net/edu/ebg/" target = "_ blank" class = "keylink"> word </a>
Order. addIdProperty ();
Property orderDate = order. addDateProperty ("date"). getProperty ();
Property customerId = order. addLongProperty ("customerId"). notNull (). getProperty ();
Order. addToOne (customer, customerId );
ToMany mermertoorders = customer. addtoorders (order, customerId );
CustomerToOrders. setName ("orders ");
CustomerToOrders. orderAsc (orderDate );
}
}
In the main method, the analysis is as follows:
Schema schema = new Schema (3, "de. greenrobot. daoexample ");
The first parameter of this method is used to update the database version number, and the second parameter is the package path of the DAO class to be generated.
Create a table and set the project path of the target project to generate the DAO file.
AddNote (schema );
AddCustomerOrder (schema );
New DaoGenerator (). generateAll (schema, "../DaoExample/src-gen ");
The directory name src-gen needs to be manually created before running; otherwise, an error is reported.
If the following error occurs after running, import the dao. ftl file of the DaoGenerator project (or directly use DaoGenerator to generate the DAO file ).
After running, the following prompt is displayed, indicating that the DAO file is automatically generated successfully. Refresh the DaoExample project and you will see it.
After running, we can see that under the src-gen DaoExample project, 8 files, 3 object objects, 3 dao, 1 DaoMaster, and 1 DaoSession are automatically generated.
3. Create a table
Create an object class
Entity note = schema. addEntity ("Note ");
The default table name is the class name. You can also customize the table name.
Dao. setTableName ("NoteList ");
GreenDAO automatically creates table fields based on object class attributes and assigns the default values. For example, the table name and column name in the database are derived from the object class name and attribute name. By default, database names are separated by underscores (_) in upper case rather than in Java. For example, a database column named "CREATIONDATE" will become "CREATION_DATE ".
Set an auto-increment ID column as the primary key:
Dao. addIdProperty (). primaryKey (). autoincrement ();
Set other types of attributes:
Dao. addIntProperty ("cityId ");
Dao. addStringProperty ("infoType"). notNull (); // non-null field
Dao. addDoubleProperty ("Id ");
In the generated object class, the int type is automatically converted to the long type.
If the following error occurs during compilation, it may be caused by a primary key type error:
Java. lang. ClassCastException: java. lang. Integer cannot be cast to java. lang. String
When greenDAO is used, one entity class can only correspond to one table. Currently, one table cannot correspond to multiple entity classes, or multiple tables share one object type. Subsequent upgrades will not be used for this purpose.
4. add, delete, modify, and query tables
It is quite convenient to add, delete, modify, query, and completely object-oriented. It does not need to involve any SQL language.
Query
Example 1: query whether a table contains an id:
Public boolean isSaved (int ID)
{
QueryBuilder <SaveList> qb = saveListDao. queryBuilder ();
Qb. where (Properties. Id. eq (ID ));
Qb. buildCount (). count ();
Return qb. buildCount (). count ()> 0? True: false;
}
Example 2: obtain the data set of the entire table. You can use a single code!
Public List <PhotoGalleryDB> getPhotoGallery ()
{
Return photoGalleryDao. loadAll (); // obtain the image album
}
Example 3: Use one field value to find another field value (to make it easy to use the following method directly, there may be a simpler method, but you have not tried it yet)
/** Search for its directory id through the image id */
Public int getTypeId (int picId)
{
QueryBuilder <PhotoGalleryDB> qb = photoGalleryDao. queryBuilder ();
Qb. where (Properties. Id. eq (picId ));
If (qb. list (). size ()> 0)
{
Return qb. list (). get (0). getTypeId ();
}
Else
{
Return-1;
}
}
Example 4: Find all the first names are "Joe" and sorted by lastname.
List joes = userDao. queryBuilder ()
. Where (Properties. FirstName. eq ("Joe "))
. OrderAsc (Properties. LastName)
. List ();
Example 5: Multi-condition Query
(1) obtain the data set whose id is cityId and whose infotype is HBContant. CITYINFO_SL:
Public List <CityInfoDB> getSupportingList (int cityId)
{
QueryBuilder <CityInfoDB> qb = cityInfoDao. queryBuilder ();
Qb. where (qb. and (Properties. CityId. eq (cityId), Properties. InfoType. eq (HBContant. CITYINFO_SL )));
Qb. orderAsc (Properties. Id); // sort
Return qb. list ();
}
(2) obtain all user sets whose firstname is "Joe" and which were born after January 1, October 1970:
QueryBuilder qb = userDao. queryBuilder ();
Qb. where (Properties. FirstName. eq ("Joe "),
Qb. or (Properties. YearOfBirth. gt (1970 ),
Qb. and (Properties. YearOfBirth. eq (1970), Properties. MonthOfBirth. ge (10 ))));
List youngJoes = qb. list ();
Example 6: Get a column object
PicJsonDao. loadByRowId (picId );
5. Add/insert and modify
It is easier to insert data, but it can be done with just one piece of code!
Public void addToPhotoTable (Photo p)
{
PhotoDao. insert (p );
}
A new object is required during insertion. An example is as follows:
DevOpenHelper helper = new DaoMaster. DevOpenHelper (this, "notes-db", null );
Db = helper. getWritableDatabase ();
DaoMaster = new DaoMaster (db );
DaoSession = daoMaster. newSession ();
NoteDao = daoSession. getNoteDao ();
Note note = new Note (null, noteText, comment, new Date ());
NoteDao. insert (note );
Modify and update:
PhotoDao. insertOrReplace (photo );
PhotoDao. insertInTx (photo );
6. Delete:
(1) Clear table data
/** Clear the data in the album image list */
Public void clearPhoto ()
{
PhotoDao. deleteAll ();
}
(2) Delete an object
{
QueryBuilder <DBCityInfo> qb = cityInfoDao. queryBuilder ();
DeleteQuery <DBCityInfo> bd = qb. where (Properties. CityId. eq (cityId). buildDelete ();
Bd.exe cuteDeleteWithoutDetachingEntities ();
}
It can be seen from the above that it is convenient to use greenDAO to add, delete, modify, and query databases, and it has excellent performance.
Iii. Notes on common methods
1. How to obtain the DaoMaster and DaoSession in the Application implementation:
Private static DaoMaster daoMaster;
Private static DaoSession daoSession;
/**
* Obtain the DaoMaster
*
* @ Param context
* @ Return
*/
Public static DaoMaster getDaoMaster (Context context)
{
If (daoMaster = null)
{
OpenHelper helper = new DaoMaster. DevOpenHelper (context, HBContant. DATABASE_NAME, null );
DaoMaster = new DaoMaster (helper. getWritableDatabase ());
}
Return daoMaster;
}
/**
* Get DaoSession
*
* @ Param context
* @ Return
*/
Public static DaoSession getDaoSession (Context context)
{
If (daoSession = null)
{
If (daoMaster = null)
{
DaoMaster = getDaoMaster (context );
}
DaoSession = daoMaster. newSession ();
}
Return daoSession;
}
2. add, delete, modify, and query tools:
Public class DBHelper
{
Private static Context mContext;
Private static DBHelper instance;
Private CityInfoDBDao cityInfoDao;
Private DBHelper ()
{
}
Public static DBHelper getInstance (Context context)
{
If (instance = null)
{
Instance = new DBHelper ();
If (mContext = null)
{
MContext = context;
}
// Database object
DaoSession daoSession = HBApplication. getDaoSession (mContext );
Instance. cityInfoDao = daoSession. getCityInfoDBDao ();
}
Return instance;
}
/** Add data */
Public void addToCityInfoTable (CityInfo item)
{
CityInfoDao. insert (item );
}
/** Query */
Public List <EstateLoveListJson> getCityInfoList ()
{
QueryBuilder <CityInfo> qb = cityInfoDao. queryBuilder ();
Return qb. list ();
}
/** Query */
Public List <CityInfo> getCityInfo ()
{
Return cityInfoDao. loadAll (); // search for an image album
}
/** Query */
Public boolean isSaved (int Id)
{
QueryBuilder <CityInfo> qb = cityInfoDao. queryBuilder ();
Qb. where (Properties. Id. eq (Id ));
Qb. buildCount (). count ();
Return qb. buildCount (). count ()> 0? True: false; // search for a favorite table
}
/** Delete */
Public void deleteCityInfoList (int Id)
{
QueryBuilder <CityInfo> qb = cityInfoDao. queryBuilder ();
DeleteQuery <CityInfo> bd = qb. where (Properties. Id. eq (Id). buildDelete ();
Bd.exe cuteDeleteWithoutDetachingEntities ();
}
/** Delete */
Public void equalityinfo ()
{
CityInfoDao. deleteAll ();
}
/** Search for its type id by city id */
Public int getTypeId (int cityId)
{
QueryBuilder <CityInfo> qb = cityInfoDao. queryBuilder ();
Qb. where (Properties. Id. eq (cityId ));
If (qb. list (). size ()> 0)
{
Return qb. list (). get (0). getTypeId ();
}
Else
{
Return 0;
}
}
/** Multi-query */
Public List <CityInfo> getIphRegionList (int cityId)
{
QueryBuilder <CityInfoDB> qb = cityInfoDao. queryBuilder ();
Qb. where (qb. and (Properties. CityId. eq (cityId), Properties. InfoType. eq (HBContant. CITYINFO_IR )));
Qb. orderAsc (Properties. Id); // sort
Return qb. list ();
}
}
In addition, there are multiple table associations, inert loading, and other functions to be studied in the future.
References:
1. https://github.com/greenrobot/greenDAO
2. http://greendao-orm.com/documentation/how-to-get-started/
3. http://blog.csdn.net/krislight/article/details/9391455