Introduction to Android ORMLite database, androidormlite
Zookeeper
In general projects, the SQLite database provided by Android can meet the requirements of lightweight data storage applications. However, as long as the storage model is a slightly complex project and the data structure model is complex, it is difficult to use SQLite to support data storage for the entire project. Besides, it is not easy to maintain and manage the code written using SQLite. Therefore, in a large-scale project, it is necessary to introduce a developer-friendly third-party ORM database framework: ORMlite.
ORMLite official introduction: "Object Relational Mapping Lite (ORM Lite) provides some simple, lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages. ".
ORMLite is a lightweight SQL database development kit (packages) for Object Relational ing databases ). Provides easy-to-use DAO.
ORMLite official homepage: http://ormlite.com
It is written in Java and supports Java and Android platforms. This article focuses on how to use ORMLite in Android application development.
Use ORMLite in Android Application Development, first download ORMLite development jar package, jar package download home page: http://ormlite.com/releases
Specifically to Android, You need to download two jar packages on the http://ormlite.com/releases page (this article based on ORMLite version is: ormlite 4.49-SNAPSHOT ):
(1) jar packages in the core list;
(2) jar packages in the android list.
:
Download the two jar packages and place them in the libs package of the Android project ,:
After the preceding steps are completed, the ORMLite development environment is set up and can be used later.
First, you must create and define a database table that ORMLite uses to store. This table is implemented using a Java class, such as User. java:
Package zhangphil. ormlitetest. database; import com. j256.ormlite. field. databaseField; import com. j256.ormlite. table. databaseTable; @ DatabaseTable (tableName = "users") public class User {public final static String USER_ID = "user_id"; public final static String NAME = "name "; public final static String AGE = "age"; public User () {} public User (String name, int age) {this. name = name; this. age = age;} // @ DatabaseField (generatedId = true) // public int id; @ DatabaseField (id = true, columnName = USER_ID) public int user_id; @ DatabaseField (columnName = NAME) public String name; @ DatabaseField (columnName = AGE) public int age; public int getUserId () {return user_id;} public void setUserId (int uid) {this. user_id = uid;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}@ Overridepublic String toString () {return "user_id:" + user_id + "name:" + name + "age:" + age ;}}
The above Java class User starts a piece of code:
@DatabaseTable(tableName = "users")
This Code declares the data model defined in the User class and stores it in the database table "users. In other words, in the database table users, the stored data unit is also the data model defined in the class User.
Where:
@ DatabaseField (columnName = "xxx ")
Xxx indicates the column name of this data field in the database table.
In DatabaseField, if id = true is set, this id is declared as the primary key.
ORMLite database tables have many configurable parameters. For more information, see the official documentation. The rest is to create an ORMLite database, which is similar to SQLite. ORMLite query, insertion, deletion, and modification mainly use DAO.
A simple code is provided:
Define an ORMLite database table User. java. Assume that the User table stores the User's id, name, and age information:
Package zhangphil. ormlitetest. database; import com. j256.ormlite. field. databaseField; import com. j256.ormlite. table. databaseTable; @ DatabaseTable (tableName = "users") public class User {public final static String USER_ID = "user_id"; public final static String NAME = "name "; public final static String AGE = "age"; public User () {} public User (String name, int age) {this. name = name; this. age = age;} // @ DatabaseField (generatedId = true) // public int id; @ DatabaseField (id = true, columnName = USER_ID) public int user_id; @ DatabaseField (columnName = NAME) public String name; @ DatabaseField (columnName = AGE) public int age; public int getUserId () {return user_id;} public void setUserId (int uid) {this. user_id = uid;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}@ Overridepublic String toString () {return "user_id:" + user_id + "name:" + name + "age:" + age ;}}
Create ORMLite database management tool class ORMLiteDatabaseHelper. java:
Package zhangphil. ormlitetest. database; import java. SQL. SQLException; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteDatabase. cursorFactory; import android. util. log; import com. j256.ormlite. android. apptools. ormLiteSqliteOpenHelper; import com. j256.ormlite. dao. dao; import com. j256.ormlite. support. connectionSource; import com. j256.ormlite. ta Ble. tableUtils; public class ORMLiteDatabaseHelper extends {private static ORMLiteDatabaseHelper mDatabaseHelper = null; private Dao <User, Integer> mUserDao = null; private final static String DataBase_NAME = "ormlite. db "; private final static int DataBase_VERSION = 1; public ORMLiteDatabaseHelper (Context context, String databaseName, CursorFactory factory, int databaseVersion ){ Super (context, DataBase_NAME, factory, DataBase_VERSION);} public static ORMLiteDatabaseHelper getInstance (Context context) {if (mDatabaseHelper = null) {mDatabaseHelper = new partition (context, DataBase_NAME, null, dataBase_VERSION);} return mDatabaseHelper;} @ Overridepublic void onCreate (SQLiteDatabase arg0, ConnectionSource connectionSource) {Log. d (this. getClass (). getName (), "ORMLite data Database-> onCreate "); try {TableUtils. createTableIfNotExists (connectionSource, User. class);} catch (Exception e) {e. printStackTrace () ;}@ Overridepublic void onUpgrade (SQLiteDatabase database, ConnectionSource arg1, int arg2, int arg3) {Log. I (this. getClass (). getName (), "database-> onUpgrade"); try {// Delete the old database table. TableUtils. dropTable (connectionSource, User. class, true); // create a new database. OnCreate (database, connectionSource);} catch (SQLException e) {e. printStackTrace () ;}/ *** each database table must have a method to obtain Dao. You can use a more common template method such as ** public Dao <Class, Integer> getORMLiteDao (Class cls) throws SQLException {* if (dao = null) {dao = getDao (cls);} ** return dao;} */public Dao <User, Integer> getUserDao () {if (mUserDao = null) {try {mUserDao = getDao (User. class);} catch (java. SQL. SQLException e) {e. printStackTrace () ;}} return mUserDao ;}@ Overridepublic void close () {super. close (); mUserDao = null ;}}
Then, you can directly use it in your own applications:
Package zhangphil. ormlitetest; import java. SQL. SQLException; import java. util. list; import java. util. random; import com. j256.ormlite. dao. dao; import zhangphil. ormlitetest. database. ORMLiteDatabaseHelper; import zhangphil. ormlitetest. database. user; import android. support. v7.app. actionBarActivity; import android. widget. toast; import android. OS. bundle; public class MainActivity extends ActionBarActivity {private Dao <User, Integer> mUserDao; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); ORMLiteDatabaseHelper mDatabaseHelper = ORMLiteDatabaseHelper. getInstance (this); mUserDao = mDatabaseHelper. getUserDao (); Random rand = new Random (); for (int I = 0; I <3; I ++) {User user User = new user (); User. setUserId (I); user. setName ("name" + I); // generate the age of the random test. User. setAge (rand. nextInt (100); try {mUserDao. createOrUpdate (user);} catch (SQLException e) {e. printStackTrace () ;}}@ Overridepublic void onStart () {super. onStart (); // global query try {List <User> users = mUserDao. queryForAll (); for (User u: users) {Toast. makeText (this, u. toString (), Toast. LENGTH_SHORT ). show () ;}} catch (SQLException e) {e. printStackTrace ();} // condition query QueryBuilder // assume that we have given a User id = 1int uid = 1; try {List <User> users = mUserDao. queryBuilder (). where (). eq (User. USER_ID, uid ). query (); for (User u: users) {Toast. makeText (this, "query result:" + u. toString (), Toast. LENGTH_SHORT ). show () ;}} catch (SQLException e) {e. printStackTrace ();}}}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.