Some advanced usage of the android GreenDao framework, Android greendao
It can be roughly divided into the following aspects:
- Sort query commands
- Use SQL statements for special queries
- Check whether the table field exists
- Database Upgrade
- Database Table field assigned Initial Value
I. Sorting Out query commands 1. chained execution commands
return mDaoSession.getUserDao().queryBuilder(). XXX. XXX. XXX. list();
In general, the query statement adds various judgment and filtering method commands to the intermediate xxx position, except that the final ending command list () or unique () returns a set or business object, others return QueryBuilder objects. In most cases, the XXX position is filled with the where statement, and some other SQL-related statements are easy to use.
The conditions written in the where Statement of "whereOr" are connected with "and", and the statements in whereOr are connected with "or ".
"Distinct" directly filters out overload Fields
"Limit" pages n pages, usually used in combination with offset
"Offset" ignores the first n results
"OrderAsc" is sorted in ascending order of fields
"OrderDesc" in descending order of fields
"PreferLocalizedStringOrder" localized string sorting
The "orderCustom" Custom sorting requires two parameters: one attribute and the corresponding sorting scheme ASC or DESC.
"OrderRaw" is also a custom sorting, and the field and sorting scheme are written in a string to pass in
"StringOrderCollation" is also a custom sorting that can merge multiple ascending/descending sorting schemes in ascending order of dates and in descending order of prices.
2. COMMANDS IN THE CONDITION
return mDaoSession.getUserDao().queryBuilder(). where(UserDao.Properties.UserId.in(userIdList), UserDao.Properties.UserAge.eq(19)). list();
A simple where statement is like this. Many conditions can be written in the brackets of where, all of which are connected with "and. In addition to the above "in" and "eq", there are many other judgment Conditions
"NotEq" is the opposite of eq. Don't be dumb and try again "!" Invert
"NotIn" is the same as above
"Or" or
"Like" is the SQL statement LIKE "%" + string + "%"
"Between" is? AND? You can take the interval of two values (but this statement should be used with caution. Different databases are different. Some are A <condition <B, and some are A <= condition <= B)
"Gt" is equivalent to>
"Ge" is equivalent to> =
"Lt" is equivalent to <
"Le" is equivalent to <=
"IsNull" is null
"NotIsNull" is not empty
Ii. use SQL statements for special queries
This rawQuery method is usually used when common addition, deletion, modification, and query operations cannot be easily implemented. I often encounter two scenarios:
1. Use SELECT DISTINCT
It is often related to one-to-many relationship. Assume that the library now has a "User book table", and some users have 20 books, each of which corresponds to a different book.
In this case, we assume that there is a requirement to find out all the usernames in this table. Do not repeat them. At this time, it will be very troublesome to use common query commands. You need to use the select distinct command to find all the entries in a column name that are not repeated.
String queryString = "SELECT DISTINCT " + UserBookDao.Properties.UserName.columnName + " FROM " + UserBookDao.TABLENAME + " ORDER BY " + UserBookDao.Properties.CreatedTime + " DESC " + " LIMIT " + page * LIMIT_NUM + " , " + LIMIT_NUM; ArrayList<String> result = new ArrayList<>(); Cursor c = mDaoSession.getDatabase().rawQuery(queryString,new String[]{}); try { if (c != null) { if (c.moveToFirst()) { do { result.add(c.getString(0)); } while (c.moveToNext()); } } } finally { if (c != null) { c.close(); } }
The style of the Code is like this. First, We splice a string that conforms to the SQL syntax and randomly Add a write command field to sort and pagination, make the query command look more complete, and then use the cursor to receive the above query results.
Most queries may contain some parameters, such as the filter condition where XX = XX. If you have a requirement, you need to add a limit on the prices of publishers and books in the previous query, the query method is as follows:
String queryString = "select distinct" + UserBookDao. properties. userName. columnName + "FROM" + UserBookDao. TABLENAME // Dong baoran blog Park + "WHERE" + UserBookDao. properties. publisher. columnName + "=? "+" AND "+ UserBookDao. Properties. Price. columnName +">? "+" Order by "+ UserBookDao. properties. createdTime + "DESC"; ArrayList <String> result = new ArrayList <> (); Cursor c = mDaoSession. getDatabase (). rawQuery (queryString, new String [] {"a publishing house"), String. valueOf (100.00)}); try {if (c! = Null) {if (c. moveToFirst () {do {result. add (c. getString (0);} while (c. moveToNext () ;}} finally {if (c! = Null) {c. close ();}}
The query string with parameters must use the question mark placeholder above, and then fill in the relevant input parameters in the following rawQuery api with parameters.
2. SELECT queries multiple fields at the same time
Let's look at the example of this book. Suppose we want to look up three fields: "book name", "publisher", and "price ".
String queryString = "SELECT" + UserBookDao. TABLENAME + ". "+ UserBookDao. properties. bookName. columnName + "," + UserBookDao. TABLENAME + ". "+ UserBookDao. properties. publisher. columnName + "," + UserBookDao. TABLENAME + ". "+ UserBookDao. properties. price. columnName + "" + "FROM" + UserBookDao. TABLENAME + "" + "WHERE" + UserBookDao. properties. price + "> 100.00"; Cursor cursor = null; try {curs Or = session. getDatabase (). rawQuery (queryString, new String [] {}); if (cursor = null) {return payMap;} // retrieve the indexes corresponding to the three fields, the value int nameIndex = cursor is taken for the index. getColumnIndex (UserBookDao. properties. bookName. columnName); int publisherIndex = cursor. getColumnIndex (UserBookDao. properties. publisher. columnName); int priceIndex = cursor. getColumnIndex (UserBookDao. properties. price. columnName); if (nameIndex! =-1 & publisherIndex! =-1 & priceIndex! =-1) {while (cursor. moveToNext () {String name = cursor. getString (nameIndex); String publisher = cursor. getString (publisherIndex); Double price = cursor. getDouble (priceIndex); // the three fields are stored in the model or processed by the dictionary. }}} Finally {if (null! = Cursor) {cursor. close ();}}
The following three required fields can be retrieved at a time for use. You need to obtain the corresponding index of the field before the index value.
3. Check whether the table field exists
private boolean hasColumn(SQLiteDatabase db, String tableName, String column) { if (TextUtils.isEmpty(tableName) || TextUtils.isEmpty(column)) { return false; } Cursor cursor = null; try { cursor = db.query(tableName, null, null, null, null, null, null); if (null != cursor && cursor.getColumnIndex(column) != -1) { return true; } } finally { if (null != cursor) { cursor.close(); } } return false; }
Similar to the method used to retrieve the cursor above, if the retrieved column index value is not-1, true is returned if this field is obtained. Otherwise, fasle is returned when the input parameter is invalid.
4. Database Upgrade
This method will be called to determine whether the column name already exists.
Then rewrite the onUpgrade method of the parent class.
Private static class DemoOpenHelper extends DaoMaster. openHelper {public DemoOpenHelper (Context context, String name, SQLiteDatabase. cursorFactory factory) {super (context, name, factory) ;}@ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// The Version Control of the database can increase the difference value as the version overlays. if (oldVersion <2) {if (! HasColumn (db, UserBookDao. TABLENAME, UserBookDao. properties. author. columnName) {String SQL = "alter table" + UserBookDao. TABLENAME + "add COLUMN" + UserBookDao. properties. author. columnName + "TEXT"; db.exe cSQL (SQL);} if (! HasColumn (db, UserBookDao. TABLENAME, UserBookDao. properties. type. columnName) {String SQL = "alter table" + UserBookDao. TABLENAME + "add COLUMN" + UserBookDao. properties. type. columnName + "INTEGER"; db.exe cSQL (SQL );}}}}
In addition to the above table modification, if there are too many changes or changes, it indicates that you can also directly Delete and recreate the table (in this case, the previous data will be deleted)
if (oldVersion < 3) { UserDao.dropTable(new StandardDatabase(db),true); UserStudentDao.createTable(new StandardDatabase(db),true); }V. Assigning initial values to database table fields
If you do not want the initial value of some fields to be 0 or an empty string, you can assign the initial value. The initial values of values can be divided into two situations.
1. Add an initial value when creating a table
In versions earlier than 3.0, you still need to write a module with similar code to create a table.
private static void addUser(Schema schema) { Entity user = schema.addEntity("User"); user.addIdProperty(); user.addStringProperty("name").notNull().defValue("\"jack\""); user.addStringProperty("address"); user.addStringProperty("teacher"); user.addIntProperty("age").primJavaType().defValue("17"); }
After 3.0, annotations and Entity writing are implemented, so you can directly specify
@ Entitypublic class Student {@ Id (autoincrement = true) private long id; // primary key private String name; private String schoolTime = "09-01 "; // The default start time is September 1 private int age = 19; // when I first went to college, the default value is 19 years old. // The getter and setter generated below are omitted ...}
2. assign an initial value to the update field during Database Upgrade
To upgrade the database, you need to write an alter table SQL statement, which can be directly spliced to the end of this line.
// Check whether the column name exists //... string SQL = "alter table" + UserBookDao. TABLENAME + "add COLUMN" + UserBookDao. properties. type. columnName + "INTEGER" + "not null default (-1)"; // directly concatenate the statement at the end of the statement. Dong baoran blog garden db.exe cSQL (SQL );//...
Note: I have heard of a saying that the DEFAULT statement is directly spliced after the created statement in the class generated by UserDao, which is very opposed here, first, the class name clearly indicates // this code is generated by greenDAO, do not edit. some people may set the code to be manually generated, but our project is set in gradle to automatically generate each build, which will be overwritten every time.
Make some preparations during development. You are welcome to discuss it.