Android Rapid Development--using Ormlite to operate the database

Source: Internet
Author: User

Ormlite is an open-source framework for database operations assistance, primarily for the Java language. In the Android database development, is a more popular open source framework, easy to operate and powerful, today to learn about, the recent project has also been involved in, write a blog to remember, thank God team contributed so useful open source framework, here is Ormlite official website: http ://ormlite.com/

Preparation – Create database and data tables

Ormlite with Java annotations to establish a mapping relationship with the database, here we have an example to illustrate, as we now want to build a simple database test.db and create a table person to record one's name, age, address and so on.

To create a bean class

First, we build our bean class person and associate it with the database by annotating it.

@DatabaseTable(TableName ="Person") Public  class  person {    @DatabaseField(generatedid=true)Private intId@DatabaseField(columnname="Name")PrivateString name;@DatabaseField(columnname="Age")Private intAge@DatabaseField(columnname="Address")PrivateString address;/** * @return the ID */     Public int getId() {returnId }/** * @param ID The ID to set */     Public void setId(intID) { This. id = ID; }/** * @return the name * *     PublicStringGetName() {returnName }/** * @param Name The name to set */     Public void SetName(String name) { This. name = name; }/** * @return  The age * *     Public int Getage() {returnAge }/** * @param  age-The age-to set */     Public void Setage(intAge) { This. Age = Age; }/** * @return the address * *     PublicStringgetaddress() {returnAddress }/** * @param address the address to set */     Public void setaddress(String address) { This. address = Address; }}

Here we create the Bean class and connect to the database, two things we need to do
1. Need to fill in the table name in the @databasetable annotation
2. Fill in the field name in @databasefield (columnname= ""), set the properties of the field, etc.

Field Property Description

Ormlite provides us with comprehensive support for field properties, let's take a look at the details below:

    • Cloumnname: Specifies the field name, without specifying the variable name as the field name
    • Canbenull: Whether it can be null
    • DataType: Specifies the type of field
    • Foreign specifies that the object of this field is a foreign key, and the foreign key value is the ID of this object
    • If the Foreignautocreate foreign key does not exist, it is automatically added to the external table
    • Foreignautorefresh foreign key value, auto refresh
    • Foreigncolumnname which field in the Foreign key table is specified by the Foreign key field
    • Generatedid: Specifies the ID of the field to grow from, and cannot id,generatedidsequence generic
    • ID: Specify Field ID
    • Index: Indexed
    • Persisted: Specifies whether this variable is persisted, by default true
    • Throwifnull if a null value throws an exception
    • Usegetset: Specifies that the Ormlite access variable uses the Set,get method by default using the reflection mechanism to directly access the variable
    • Unique: Field value unique
    • Uniqueindex Unique Index
    • Uniquecombo the value of the whole column is unique
Create a database

Similar to database creation in Android, creating a database using Ormlite requires us to create a sqlopenhelper inheritance ormlitesqliteopenhelper, There are two important methods in Ormlitesqliteopenhelper, namely OnCreate and Onupgrade, which are responsible for database creation and the operation of the upgrade.

 Public  class mysqlopenhelper extends ormlitesqliteopenhelper {    PrivateDao<person, integer> Mpersondao; Public Mysqlopenhelper(Context context) {Super(Context,"Test",NULL,1);//TODO auto-generated constructor stub}@Override     Public void onCreate(Sqlitedatabase arg0, Connectionsource arg1) {//TODO auto-generated method stub        Try{//Create data TablesTableutils.createtableifnotexists (Arg1, Person.class); }Catch(Java.sql.SQLException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }@Override     Public void Onupgrade(Sqlitedatabase arg0, Connectionsource arg1,intArg2,intARG3) {//TODO auto-generated method stub} PublicDao<person, integer>Getpersondao()throwsjava.sql.SQLException {if(Mpersondao = =NULL) {Mpersondao = Getdao (Person.class); }returnMpersondao; }}

DAO is a very important class, these DAO objects are used for future database operations, which contain two generics, the first generic table DAO operation class, and the second is the ID of the tag data table.

Database operations

After we have created our own database, we can come to the database operation, and then we will see how to make the database additions and deletions.

Insert operation

These methods are relatively simple to use, and we just need to pass our own beans into the following methods

    • Create: Insert a piece of data
    • Createifnotexists: Insert If it does not exist
    • Createorupdate: Update if it exists
Query operations

Ormlite for me to provide a series of query operations, a lot of methods, and many are just look at the method name can be known, here is not introduced, here is how to use QueryBuilder for complex lookups.

    • First Call Persondao.querybuilder (), get the QueryBuilder object under the DAO,
    • Next, set the query criteria for QueryBuilder,
    • Finally, the list object is obtained by QueryBuilder's Query method.

Here are a few common builder queries,
1. Multi-field condition query:

QueryBuilder builder = dao.queryBuilder(); builder.where().eq("字段名1","条件1").and.eq(""字段名2","条件2")

2. Query and output sequentially

QueryBuilder<PersonInteger> builder = dao.queryBuilder();builder.orderBy("字段名"true);builder.query();

Order BY method The first parameter means sort by that field, and the second parameter indicates whether it is ascending.

3. Paging Query

QueryBuilder<Person, Integer> builder = dao.queryBuilder();builder.offset(10);//表示查询的起始位置builder.limit(10);//表示总共获取的对象数量builder.query();
Delete and change actions

Similar to query operations, Ormlite also provides us with a range of methods, as well as complex deletions, complex changes of Deletebuilder and Updatebuilder, which are similar in usage to QueryBuilder, and are not described in detail.

Place the database on the SD card

Android Create a database The default storage path is under the/data/data/packagename/database directory, on the one hand if the database is large will occupy the system storage space, on the other hand, if you do not get the system root permissions, will not be able to visually see the database. So at the end of the article, how to build the database under the specified SD card directory.

This is not offered in Ormlite, write it yourself. Read the Android source code can be easily found that the Android database storage directory is the Contextwrapper class under the public File Getdatabasepath (String name) method is determined, Then we just need to create our own context to overwrite the method.

 Public  class databasecontext extends contextwrapper {    Private Static FinalString root_sdcard = environment. getExternalStorageDirectory (). GetAbsolutePath ();PrivateString Dbdir; Public Databasecontext(Context base, String Path) {Super(base);    Dbdir = path; }@Override     PublicFileGetdatabasepath(String name) {//Determine if there is an SD card        BooleanSdexist = Android.os.Environment.MEDIA_MOUNTED. Equals (Android.os.Environment.getExternalStorageState ());if(!sdexist) {//If not present,LOG.E ("Database Error","SD card does not exist");return NULL; }//Determine if the directory exists and does not exist create the directoryFile Dirfile =NewFile (Dbdir);if(!dirfile.exists ()) dirfile.mkdirs ();//Mark database file is created successfully        BooleanIsfilecreatesuccess =false; String DbPath = Dbdir +"/"+ Name;//database pathFile DBFile =NewFile (DbPath);//If the database file does not exist, create the file        if(!dbfile.exists ()) {Try{isfilecreatesuccess = Dbfile.createnewfile ();//Create file}Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }        }ElseIsfilecreatesuccess =true;//Returns the database file object        if(isfilecreatesuccess)returnDBFile;Else            return NULL; }@Override     PublicSqlitedatabaseOpenorcreatedatabase(String name,intMode, Sqlitedatabase.cursorfactory Factory) {sqlitedatabase result = Sqlitedatabase.openorcreatedatabas E (Getdatabasepath (name),NULL);returnResult }/** * Android 4.0 will call this method to get the database. *      */    @Override     PublicSqlitedatabaseOpenorcreatedatabase(String name,intMode, Cursorfactory Factory, Databaseerrorhandler ErrorHandler) {sqlitedatabase result = Sqlitedatabase . Openorcreatedatabase (Getdatabasepath (name),NULL);returnResult }}

After we create the sqlopenhelper, we simply pass in our own databasecontext, as

new SdCardDBHelper(new DatabaseContext(                MainActivity.this"person.db");
Ormlite Related documents Download

Attach Ormlite related jar files and official documentation: click to download

Android Rapid Development--using Ormlite to operate the database

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.