Use of Greendao

Source: Internet
Author: User

Use of Greendao: in general:

You need to build a generator project outside of your main Android project. This is a pure Java project.

In this project you need to refer to Greendao-generator.jar, and Freemarker.jar two jar packages in classpath. Then, in this project, use the methods in Greendao-generator to define the entities and relationships of your database. Finally, generate the DAO and Entiities code for your Android project via Freemarker. The specific definition method we'll talk about later.

Finish the above steps, the following can happily write our Android project. Don't forget, in order to use the entities and DAO methods generated by generator, we need to introduce Greendao.jar to this package in our Android project. ---------------------------------------------------------Specifically, we need to create two projects, one project is Java Engineering (not Android Engineering), is used to produce the entity class (the various getter and setter methods within this Java class are automatically created, and the attributes inside the entity class are called property, corresponding to a field in the database table. A database table for an entity class, the entity creation process will say below), build a DAO file (the DAO file is automatically produced within the various methods of querying the database, and the DAO file is created in the process below). so let's see how to generate the entity and DAO files.

1) Create Java Project (Generator project )

(2) Import Greendao-generator.jar and Freemarker.jar two packages.

(3) Create a class (all names are allowed) and create a Main method. Create a schema object in this main method , and when you create the object, you need to set the database version number, the default Java package, and so on. The default Java package is used to store the generated entity, DAO file, and test code. Such as:

Schema schema =  new Schema( 1 "de.greenrobot.daoexample" );

那么接下来就是向The schema adds the entity that you want to generate, and the property that you want in the entity (the field that corresponds to the data table). Such as:

Entity note = schema.addEntity("Note");                           note.addIdProperty();         note.addStringProperty("text").notNull();         note.addStringProperty("comment");         note.addDateProperty("date”); This automatically generates the note, the Java class, which is an object of the Entity class that corresponds to a database table, not a row of the corresponding database table, and a row of the database table corresponds to an object of the note class. Note the various property properties in this class. (For each field in a note table and note table, the tables and fields do not have to be created by themselves, where the object of the entity is generated, and there should be automatic generation of the.) )。   So, how does the DAO class of this Java class or DAO class that is used to manipulate the note table be generated? new Daogenerator (). Generateall (Schema, ".. /daoexample/src-gen "), this sentence will automatically generate the Notedao, which automatically generated the operation of the note table of various methods.   By the time we run the Java project we just created, we'll find that Daomaster, Daosession, Notedao, and note have a total of 4 classes of files. (If a number of entity objects are produced in the main method just now, there will be a number of entity objects in the DAO object, but there will only be one Daomaster, daosession to manage the objects of these entity classes ) at this point we can use the class we created in our Android project. This is the second engineering--android project we need to create.

After completing the generator work, the following things are simple:

(1) Create an Android project

(2) write an application in a. java file: Insert a note object in the note table (one row of data):

DevOpenHelper helper = newDaoMaster.DevOpenHelper(this"notes-db"null); //上面生成的entity所对应的表生成在哪个数据库中db = helper.getWritableDatabase();  daoMaster = newDaoMaster(db);  daoSession = daoMaster.newSession();  noteDao = daoSession.getNoteDao();  Note note = newNote(null, noteText, comment, newDate());  noteDao.insert(note);  noteDao.deleteByKey(id);If there are two tables, one is a note table, the other is a picture table, and a row of data for the note table corresponds to the unique row of data for the picture table, we now want to pass an instance of the entity object by Note note1 Call the Getpicture () method directly to get the row of data in the picture table (which corresponds to a row of the note table) that corresponds to the note1 (that is, the picture (Java Class) object that corresponds to a picture instance picture1) So how to get it? ?
Now that we want to get this note1 by invoking the Getpicture () method directly from the instance of the entity object Note1, we want to Addtoone () to the entity object of note, The required parameters are the picture of the entity object (the entity object, not the object's object) and the Pictureid attribute in the note class (if the note does not have a Pictureid attribute in the Java class), We need to first create this property in it, it is stated that the picture table must be implemented with Pictureid this field or the picture of the entity object (Java Class) must have this Pictureid attribute beforehand, Otherwise, it will not be based on this creation relationship query), such as:
User.addlongproperty ("Pictureid"). GetProperty ();
user.addToOne(picture, pictureIdProperty);
(The user,picture here is an object of entity, not an object of the user class or picture class) so that we can then invoke an instance of the note class (the object of which the class is an entity) note1 the Getpicture () method (get Picture's picture is the name of the table, not the Getpictureid, because what we get is really an instance of picture. Do not pass parameters, because I this note1 corresponds to the Pictureid is known, directly to the picture table has the Pictureid value of the line, so do not pass the argument, this getpicture method is we do the above steps Automatically generated) to get the row of data that corresponds to the picture table. If we still want our note1 to get directly another unique data picturesmall in the picture table (like Pictureid, the note and picture tables have this field and are the only ones that correspond because our get The picture method is an indication of the same table, which cannot be distinguished, so the name should be set again, for example:
Property pictureIdProperty = user.addLongProperty("pictureId").getProperty();Property thumbnailIdProperty = user.addLongProperty("thumbnailId").getProperty();user.addToOne(picture, pictureIdProperty);user.addToOne(picture, thumbnailIdProperty, "thumbnail");
We want to call Note1.getthumbnail () when we want to note1 the same line of picturesmall in the picture table. It was a one-to-one relationship and a couple of relationships. That is to say we are not the only picture table in the Pictureid, many lines can have the same pictureid, at this time we cannot use the Addtoone just said, but use Addtomany, So we call note1 the Note class instance's Getpictures (one more s) method, we get all the rows in the picture table Pictureid the Pictureid value in Note1 (a list is returned). Note that the list after getpcitures will be cached, and we will then take it from the cache at query time, so after deleting or adding the modified Picture database table, we will reset the cache to empty the list, the cache exists in Note1, So be note1.resetpictures (). Finally, let's look at the query: for example:

Queries all users in the name of Joe, sorted by last name.

List joes = userDao.queryBuilder().where(Properties.FirstName.eq("Joe")).orderAsc(Properties.LastName).list();

dao里面的方法都是生成dao文件时自动产生的,所以不用多讲。这里有一点不是很明白,
properties这个类是在哪里写的呢?我们知道entity类中有各种property,为什么不直接调用
那里面的property,而又创建了一个properties类?并且这个是在哪创建的?自动还是手动创建的??
都不是很清楚???

Another example of a query: nested conditions: Gets all users who were born after October 1970 named Joe. We correspond the user's birthday to the year, month, and day attributes of the entity. We use a more formal form to express the query condition as: The name is Joe and the year of the birthday is greater than 1970 or (the year of the birthday is 1970 and the month of the birthday is equal to or greater than 10))

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();
qb.or()和qb.and()都可以看成是whereConditon类型的参数传入到where()中

When you use a method of the QueryBuilder object to get the result, QueryBuilder internally uses the query class to handle it. So if you're going to query multiple times with the same conditions, you can call QueryBuilder's build () method to produce a query that doesn't need to be executed first. You can then use this query object directly for querying (call unique () or list ()) without having to create the QueryBuilder. Specific to:

If the query condition is not changed, you just need to call one of the list/again. Unique method. If the parameter changes, you must call the Setparameter method on the changed parameter. Currently, each parameter is distinguished by a 0-based index. Corresponds to the index you passed in the parameter to QueryBuilder.
The following example uses the query object to inquire "name" for Joe, which was born in 1970 for:

Query query = userDao.queryBuilder().where(Properties.FirstName.eq("Joe"), Properties.YearOfBirth.eq(1970)).build();List joesOf1970 = query.list();

Using this query object, we look for users named Marias, who were born in 1977:

query.setParameter(0, "Maria");query.setParameter(1, 1977);List mariasOf1977 = query.list();
Call query or QueryBuilder's unique () method, which will give you the only result or null if no matching entity is found. If your situation does not allow NULL as a result, call Uniqueorthrow (), which guarantees that a non-empty entity is returned ( If there is no matching result, it throws a Daoexception exception). If you expect to return multiple results at query time, you can call list ... One of the methods: The result is a typical ArrayList.Reference:
http://my.oschina.net/cheneywangc/blog/196354
http://blog.csdn.net/yuyuanhuang/article/details/42751469
                    
 

Use of Greendao

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.