Use of the android database OrmLite and androidormlite
Today we are talking about databases. I have read the solutions from other people and explained the use of ormlite databases in combination with what I actually use.
This is the third-party jar package to be imported,
SqliteOpenHelper that has used goolge knows to start to inherit
OrmLiteSqliteOpenHelper (this official Google database is a bit similar). Override its
OnCreate (SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) database creation method And OnUpgrade (SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) database Upgrade MethodThe first time you install your application onUpgrade when creating a database, onCreate processes the database table. When you upgrade the application to a new version
Public class DatabaseHelper extends OrmLiteSqliteOpenHelper {/** database version */private static final int DATABASE_VERSION = 2; <span style = "white-space: pre "> </span>/** database name */<span style =" white-space: pre "> </span> public static final String DATABASE_NAME =" fframework. db "; public DatabaseHelper (Context context) {super (context, DATABASE_NAME, null, DATABASE_VERSION);} private static DatabaseHelper mHelper ;/** * OpenHelper automatically released in three minutes ** @ return */public static DatabaseHelper getOpenHelper () {// resetTimer (); // if (Thread. currentThread () = logoff. getMainLooper (). getThread () {// throw new IllegalArgumentException ("the main thread cannot perform database operations! "); //} If (mHelper! = Null) {return mHelper;} return mHelper = OpenHelperManager. getHelper (FFApplication. app, DatabaseHelper. class);} private static Timer timer; private static int freeTime = 0;
<Span style = "white-space: pre;"> </span> // timer. The timer database is closed within the modification time.
Private static void resetTimer () {if (timer = null) {timer = new Timer (); timer. schedule (new TimerTask () {@ Overridepublic void run () {freeTime ++; if (freeTime> 180) {timer. cancel (); timer = null; freeTime = 0; mHelper. close (); mHelper = null ;}}, 1000,100 0) ;}else {freeTime = 0 ;}< span style = "white-space: pre "> </span> // create a database. Here, three tables are created: @ Overridepublic void onCreate (SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {try {TableUtils. createTable (connectionSource, Queue. class); TableUtils. createTable (connectionSource, Table. class); TableUtils. createTable (connectionSource, Sound. class); Dao <Queue, Integer> dao = DaoManager. createDao (connectionSource, Queue. class); Dao <Table, Integer> dao1 = DaoManager. createDao (connectionSource, Table. class);} catch (SQLException e) {Log. e (DatabaseHelper. class. getName (), "Unable to create datbases", e) ;}< span style = "white-space: pre "> </span> // update Database @ Overridepublic void onUpgrade (SQLiteDatabase db, ConnectionSource connectionSource, int oldVer, int newVer ){}}
- @ DatabaseTable (tableName = "student") tableName indicates
- Public ClassStudent {
- Public Static FinalString ID = "student_id ";
- Public Static FinalString NAME = "student_name ";
- Public Static FinalString LASTNAME = "student_lastname ";
- Public Static FinalString RESOURCE = "student_resource ";
- Public Static FinalString TEACHER_ID = "tacher_id ";
- @ DatabaseField (generatedId =True, UseGetSet =True, ColumnName = ID)
- Private IntId;
- @ DatabaseField (foreignColumnName = Teacher. ID, foreign =True, ForeignAutoCreate =True)
- PrivateTeacher teacher_id;
- @ DatabaseField (useGetSet =True, ColumnName = NAME)
- PrivateString name;
- @ DatabaseField (useGetSet =True, ColumnName = LASTNAME)
- PrivateString lastName;
- @ DatabaseField (useGetSet =True, ColumnName = RESOURCE)
- Private DoubleResource;
- A series of set get methods...
| CloumnName: Specifies the field name. If this parameter is not specified, the variable name is used as the field name. |
CanBeNull: can it be null? |
|
| DataType: Specifies the field type. |
DefaultValue: Specifies the default value. |
Width: specify the length. |
| Id: id of the specified field |
GeneratedId: the id of the specified field that is auto-incrementing. It cannot be an id. generatedIdSequence is common. |
Foreign specifies that the object of this field is a foreign key, and the foreign key value is the id of this object |
| UseGetSet: specifies that set is used for ormlite access variables. By default, the get method uses the reflection mechanism to directly access variables. |
ThrowIfNull. If the null value throws an exception |
Persisted: Specifies whether the variable is persistent. The default value is true. |
| Unique: unique field value |
UniqueCombo: the value of the entire column is unique. |
Index: index |
| UniqueIndex unique index |
ForeignAutoRefresh foreign key value, automatically refreshed |
Whether to add the foreign key to the foreign table if the foreign key foreignAutoCreate does not exist |
| Which field in the foreign key table specified by the foreignColumnName foreign key field |
|
|
@ ForeignCollectionField indicates that the data in this table is a foreign key in other tables (a field in other tables uses @ DatabaseField (foreignColumnName = id key name of a table, foreign = true)
The eager indicates whether the collection is retrieved when the object is initialized, whether the object is retrieved or when the traversal is performed, and the size () method also causes the traversal.
The annotation field can only be a ForeignCollection <T> or Collection <T> object.
TableUtils
Next we will introduce TableUtils to complete the creation, deletion, and clearing of tables in the data. You just need to take a look at its static method.
Dao <T, V>
Contains two generic types: the first generic table DAO operation class and the second primary key type that represents the operation class.
Main Methods:
Create: Insert a data entry
CreateIfNotExists: insert if it does not exist
CreateOrUpdate: Update if id is specified
QueryForId: More id Search
Update to find data
Refresh explanation: If you want to use other elds in the Account, you must call refresh on the accountDao class to get the Account object lled in.
Delte delete data
QueryBuilder () creates a Query Builder for complex queries.
DeleteBuilder () creates a deletion builder and deletes complex process conditions.
UpdateBuilder () creates a condition generator to modify Complex Conditions
Condition finder DeleteBuilder, QueryBuilder, UpdateBuilder
The Finder is used to help concatenate conditional statements. for example, the finder has the where () method and () method eq () method lt () method qt () method between method, which is intuitive .. it's easy to understand what it means
Finally, use the prepare () method to generate conditions and use the DAO. query | DAO. delete | DAO. update Method for execution.
You can use the orderby limit offset method of QueryBuilder to sort by page,
// This piece encapsulates a thread. Because it is time-consuming to operate the database and cannot be placed in the main thread, a thread is written to operate the database, using the executTask method will automatically implement the two methods in the Dbtask interface, and put the operation database into the onExecut () method for non-time-consuming operations into the onOk () method
private static final ExecutorService taskExecutor = Executors.newSingleThreadExecutor(); public static interface DbTask { void onExecut(); void onOK(); } private static class Execution implements Runnable { private DbTask task; public Execution(DbTask task) { this.task = task; } @Override public void run() { task.onExecut(); FFApplication.runOnUiThread(new CallBack(task)); } } private static class CallBack implements Runnable { private DbTask task; public CallBack(DbTask task) { this.task = task; } @Override public void run() { task.onOK(); } } public static void executTask(final DbTask task) { taskExecutor.execute(new Execution(task)); }