Greendao Official document translation (bottom)

Source: Internet
Author: User

The Fifth Article inquiry

The query returns entities that meet some specific criteria. You can use the original SQL to customize the query statement, or a better way: Use the Greendao querybuilder API. The query also supports the lazy-loading result set. This saves memory and performance when you manipulate a large number of result sets.

QueryBuilder

QueryBuilder can help you build a custom query statement without using SQL. Not everyone likes to write SQL statements, and of course it's easy to make mistakes that are only found when they're running. And QueryBuilder is easy to use, saving you time in writing SQL statements. Of course, because syntax validation is performed at compile time, it is difficult to find a bug in a query statement.
The compile time of the QueryBuilder verifies the reference to the property so that the bug can be discovered in code-generated ways after Greendao.
For example: Find all users with "Joe" as first name and sort by last name:

List joes = userdao.querybuilder (). where (Properties.FirstName.eq ("Joe")). ORDERASC ( properties.lastname). List ();

Nesting cases :

Get users whose names are "Joe" and are born after September 1970
Here's a description: The user's birthday is a separate attribute for Year,month, and day. We can express this condition in a more normal way:
First name is ' Joe ' and (year of birth was greater than 1970 OR (year of Birth is 1970 and month of birth are equal to OR gr Eater than (October).

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 (Ten= Qb.list ();
Query and Lazylist

The query class represents an inquiry that can be executed more than once. When you use one of the QueryBuilder methods to get results, the QueryBuilder internally uses the query class.
If you want to run more of the same query, you should call build () on QueryBuilder, to create a query instead of executing it.
Greendao supports a unique list of results and results. If you want a unique result, you can call query or QueryBuilder's unique () method, which returns a unique result when there is no matching condition, not null. If you want to prohibit the return of NULL in a use case, you can call Uniqueorthrow (), which guarantees that a non-null entity is returned. Otherwise, a daoexception will be thrown.

If you expect to return multiple entities at once, you can use the following methods:
List (): All entities are loaded into memory. The result is usually a ArrayList with no magic involved. The simplest to use.
Listlazy (): The entity loads into memory as required. Once an element in the list is accessed for the first time, it is loaded and cached for later use. Must close.
Listlasyuncached (): A "virtual" List of entities: any access to a list element causes it to be loaded from the database and must be close.
Listiterator (): Traverse the results obtained by loading (lazily) when needed, the data is not cached and must be close.
Listlazy, listlazyuncached and Listiterator classes use the Lazylist class of Greendao. To load data on demand, it holds a reference to the cursor of a database.
This is done to make sure that the lazy list and iterators (usually in the try/finally code block) are closed.
Once some elements have been accessed or traversed, the cache lazy list from Lsitlazy () and the lazy iterator from the Listiterator () method will automatically close the cursor.
However, if the list's processing is done prematurely, you should call Close () to shut down manually.

execute queries multiple times

Once you have built a query using QueryBuilder, the query object can be reused later. This is more efficient than always creating a query object repeatedly.
If the parameters of query are not changed, you just need to call the List/unique method again. If there are parameter changes, you need to call the Setparameter method to handle each change parameter.
The individual parameters are now addressed by a zero-based parameter index. The subscript is based on the parameters you passed to QueryBuilder.

Use the query object to get the user who was born in 1970 and first name is Joe:

Query query = userdao.querybuilder (). where (Properties.FirstName.eq ("Joe"), Properties.YearOfBirth.eq (1970  = Query.list ();

Using the Query object, you can query

Query.setparameter (0, "Maria"); Query.setparameter (1, 1977= Query.list ();
Executing a query in multiple threads

If you use a query in multiple threads, you must call Query Forcurrentthread () to get a query instance for the current thread. Starting from Greendao 1.3,
The instantiation of query is bound to the thread that created the query. This guarantees the security of the query object when setting parameters, and avoids interference from other threads. If other threads
If you try to set parameters on a query object or execute a query bound to another thread, an exception will be thrown. This way, you don't need a synchronization statement.
In fact, you should avoid using lock, because if you use the same query object in a concurrent transaction, a deadlock can result.
To completely avoid the potential deadlock problems, Greendao 1.3 introduces the Forcurrentthread method, which returns a thread-local instance of a query object that
It is safe to use in the current thread. When Forcueerntthread () is called every time, the parameter is set to the initialization parameter when builder constructs the query.

the original query

There are two ways to execute the original SQL to get the entity. A better way is to use QueryBuilder and wherecondition.stringcondition.
Using this method, you can pass any SQL fragment to the WHERE clause of Query Builder.
Here's a clumsy example of a subquery that uses this method to make an alternative to a federated query.

Query query = userdao.querybuilder (). where (new stringcondition ("_id in" + "(select user_id from User_ MESSAGE WHERE read_flag = 0) "). Build ();

In this example, Query Builder does not provide the features you need, and you can go back to the original Queryraw or Queryrawcreate method. They allow you to pass the original SQL strings, which are added behind the Select and entity columns. In this way, you can have a WHERE and ORDER by Statement query entity. This entity table can be referenced by the alias "T".

The following example shows how to create a query: Use federated to get the users of group named "Admin"

Query query = userdao.queryrawcreate (  ", GROUP G WHERE g.name=?) and t.group_id=g._id "," admin ");

Tips :

You can refer to the table or column name by the generated constants. This is recommended to avoid typos, because the compiler will test the names. In any entity of DAO, you can find that TABLENAME holds the name of the database and an inner class "properties". All of its properties are constants.

Delete Query

Bulk Delete Does not delete individual entities, but all entities match some criteria. In order to perform a bulk delete, create a querybuilder, call its Builddelete method, and it will return a deletequery.

This part of the API may change in the future, such as adding some more convenient methods. Remember that bulk deletion now does not affect entities in the identity scope. Before they are accessed by ID (Load method)

If they are cached, you can activate the entities that will be deleted. If the problem is caused by some use. You may consider clearing the identity scope.

Query Failure handling

If your query does not return the desired result, there are two static flags, which can open the log of SQL and parameters on QueryBuilder.

Truetrue;

They will print out SQL commands and incoming values at any time the build method is called. This way you can compare your expectations and perhaps help you copy SQL statements to some

In the SQLite Database Viewer, execute and obtain the results for comparison.

This article transferred from: http://blog.csdn.net/xushuaic/article/details/24496191

Greendao Official document translation (bottom)

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.