Android ORM Database Ormlite usage framework and Source Analysis __ Database

Source: Internet
Author: User
Tags addall sqlite java web

First, Introduction

Ormlite is a database framework, which allows us to quickly implement database operations, avoid frequent handwriting sql, improve our development efficiency, reduce the chance of error.
First you can go to its official website to see www.ormlite.com, its English full name is Object Relational Mapping, meaning is object Relationship mapping ; If you have any contact with Java EE Development, you must know that Java Web Development has a similar database mapping framework--hibernate. In simple terms, we define an entity class, using this framework, which can help us to map this entity to our database, which is sqlite in Android, and the field in the data is the member variable we define the entity.
Advantages
1) Lightweight
2 simple and easy to use
3) Package Perfect
4) Comprehensive document
Disadvantage
1) based on reflection, low efficiency
2 Lack of Chinese translation documents

second, the use of

1. Integrated
First to the Ormlite website to download the Android package: http://ormlite.com/releases/.

As you can see, the latest version is 4.49, for Android's rack: Ormlite-android-4.48.jar and Ormlite-core-4.48.jar. Copy the two jars to the Libs, and the general Gradle contains the compiled libs:

Compile Filetree (dir: ' Libs ', include: [' *.jar '])


The above frame structure can be seen after compiling.

2. Configure the Bean class

The database is certainly inseparable from the Bean class, let's look at a user class I built:

 @DatabaseTable (tablename = "User") public class User {@DatabaseField (Generatedid = True)
    private int id;
    @DatabaseField (columnName = "name") private String name;

    @DatabaseField (Canbenull = false, ColumnName = "desc") Private String desc; /* Key Ah, be sure to add a parameterless constructor for each class, and the constructor is visible in the package */public user () {} public user (string name, string desc) {th
        Is.name = name;
    THIS.DESC = desc;
    public int getId () {return id;
    The public void setId (int id) {this.id = ID;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public String GetDesc () {return desc;
    } public void Setdesc (String desc) {THIS.DESC = desc; }

}

First add @databasetable (tablename = "user") to the user class, indicating that this is a table in the database, marked as user, and then add @databasefield (columnName = "name") to the property respectively. The ColumnName value is the column name @databasefield (Generatedid = True) of the field in the data, Generatedid represents the ID as the primary key and is automatically generated, and Canbenull indicates that the property's contents cannot be empty. The following are more commonly used property settings:

Whether the
member name Data Type Description
generatedid Boolean field is automatically incremented. The default is False. A member variable in a class sets this value to tell the database to automatically increment the ID for each new record added. When a Generatedid object is created using the Dao.create () method, the database generates an ID for the record, which is returned and set into the object by the Create method. The column name of the
columnName String database. If you do not set this member name, it will be replaced with the standard form. Whether the
canbenull Boolean field can be assigned a null value. The default is true. If you set false, you must provide a value for this field every time you insert data into the database.
dataType field data type. Typically, data types are obtained from a member variable of a Java class and do not require special notes. It is equivalent to the SQL data type.
defaultvalue String The default value for a field when we create a new record in a table. By default, this value is not. The width of the
width Integer field, used primarily for string fields. The default is 0, which means the default data type and specific database defaults are used.
ID Boolean This field is an ID, and the default is False. Only one variable in a class can have this value. The column name of the
columnName String database. If you do not set this member name, it will be replaced with the standard form.

3. Encapsulate DAO class
in ordinary sqlite use, we will write a helper class to inherit Sqliteopenhelper, and then encapsulate some methods to manipulate the database, Ormlite also, But what we need to inherit is Ormlitesqliteopenhelper:

public class Databasehelper extends Ormlitesqliteopenhelper {private static final String table_name = "demo.db";

    private static context Mapplicationcontext;

    private static Databasehelper instance;

    Private map<string, dao> daomaps = new hashmap<> ();
    Private Databasehelper {Super (context, TABLE_NAME, NULL, 2);
            @Override public void OnCreate (Sqlitedatabase database, Connectionsource connectionsource) {try {
            Tableutils.createtable (Connectionsource, User.class);
        Tableutils.createtable (Connectionsource, Article.class);
        catch (SQLException e) {e.printstacktrace (); @Override public void Onupgrade (Sqlitedatabase database, Connectionsource connectionsource, int Oldversio
            n, int newversion) {try {tableutils.droptable (Connectionsource, User.class, true); Tableutils.droptable (Connectionsource, Article.class,true);
        OnCreate (database, Connectionsource);
        catch (SQLException e) {e.printstacktrace ();
        } public static void Initormlite {Mapplicationcontext = context;
    GetInstance ();
            /** * Single example gets the helper/public static Databasehelper getinstance () {if (instance = = null) {
        Syninit (Mapplicationcontext);
    return instance; Private synchronized static void Syninit {if (instance = = null) {instance =
        New Databasehelper (context); /** * Get DAO * * @return * @throws SQLException/public synchronized DAO Getdao
        (Class clazz) throws SQLException {dao DAO;

        String className = Clazz.getsimplename ();
        if (Daomaps.containskey (className)) {dao = Daomaps.get (ClassName);
         else {dao = Super.getdao (Clazz);   Daomaps.put (ClassName, DAO);
    } return DAO;
        /** * FREE resources/@Override public void Close () {super.close ();
            For (String Key:daoMaps.keySet ()) {dao DAO = Daomaps.get (key);
        DAO = null; }
    }

}

There are two ways to implement this:
To create a table, we directly use the Tableutils.createtable (Connectionsource, User.class) provided by Ormlite;

OnCreate (sqlitedatabase database,connectionsource connectionsource)

Update table: Using the tableutils.droptable provided by Ormlite (Connectionsource, User.class, true); Delete Operation ~

Onupgrade (sqlitedatabase database, Connectionsource connectionsource, int oldversion, int newversion)

I encapsulate this here as a single example, so it's generally best to initialize the OnCreate method in application:

Databasehelper.initormlite (this);

I read a lot of people's writing, like in the helper to write various methods, get a variety of DAO to operate the database, if the application data is more complicated, there will be many ways, complex is not easy to manage, like an activity written thousands of lines of code, so I am not interested to look down the way, find ways to trouble. So I only wrote a simple Getdao method in this helper, passing in the Bean class to find its corresponding DAO class, and then only to manipulate the corresponding DAO class, so that the separation is made, and I can see that I used a map to save the DAO and make a cache. Here's a look at the DAO class code I encapsulated:

public class Userdao {public static Userdao muserdaoinstance;

    Private Dao<user, integer> Muserdao;
        Public Userdao () {try {Muserdao = Databasehelper.getinstance (). Getdao (User.class);
        catch (SQLException e) {e.printstacktrace (); }} public static Userdao getinstance () {if (muserdaoinstance = null) {muserdaoinstance =
        New Userdao ();
    return muserdaoinstance;
        /** * Single INSERT data */public void Insertuser (user user) {try {muserdao.create (user);
        catch (SQLException e) {e.printstacktrace (); }/** * Multiple insert data */public void Insertusers (list<user> users) {try {MUs
        Erdao.create (users);
        catch (SQLException e) {e.printstacktrace (); }/** * Query all data/public list<user> Queryalluser () {list&Lt
        user> users = new arraylist<> ();
        try {users = Muserdao.queryforall ();
        catch (SQLException e) {e.printstacktrace ();
    return to users;
        /** * Query data by ID * * Public User Queryuserbyid (int id) {User user = null;
        try {user = Muserdao.queryforid (ID);
        catch (SQLException e) {e.printstacktrace ();
    return to user; /** * Delete the ID's data/public void Deleteuserbyid (int id) {try {Muserdao.deletebyid (
        ID);
        catch (SQLException e) {e.printstacktrace ();
            }/** * Delete the data for these IDs/public void Deleteuserbyids (list<integer> IDs) {try {
        Muserdao.deleteids (IDS);
        catch (SQLException e) {e.printstacktrace (); }/** * Delete all */public void Deletealluser () {try {MUsErdao.deletebuilder (). Delete ();
        catch (SQLException e) {e.printstacktrace (); }/** * Update current entity class data */public void UpdateUser (user user) {try {Muserdao.updat
        E (user);
        catch (SQLException e) {e.printstacktrace (); }/** * Update current Data ID/public void Updateuserbyid (user user, int id) {try {MU
        Serdao.updateid (user, id);
        catch (SQLException e) {e.printstacktrace (); }/** * Custom query/public list<user> queryby () throws SQLException {querybuilder<
        User, integer> QueryBuilder = Muserdao. QueryBuilder ();
        Where<user, integer> where = Querybuilder.where ();
        WHERE.EQ ("id", 1);
        Where.and ();

        Where.eq ("name", "xxx");
                or Muserdao.querybuilder ().
                where ().
          EQ ("id", 1). and ().      EQ ("name", "xxx");
    return Querybuilder.query (); }
}

I've also written a single case pattern here because, considering more than one place to use Userdao, the following code is used:

User user = New User ("Jianglei", "Jinling Small Overlord");
Userdao.getinstance (). Insertuser (user);

Other database operations in the same way, so that the maintenance of a database table some of the operation is relatively simple, in a class inside maintenance, want to find which database table operation, to the corresponding class of DAO inside to find the line.

After reading Ormlite, we can look at the simpler, more efficient Greendao framework, I also tidy up, we can compare: http://blog.csdn.net/qq_19711823/article/details/51837032

The following is to talk about the more boring source code analysis, no interest in children's shoes can stop.

Third, the source code analysis

1. Create a table
Let's take a look at how to create a table:

@Override public
void OnCreate (sqlitedatabase database, Connectionsource connectionsource) {
     try {
         Tableutils.createtable (Connectionsource, User.class);
     } catch (SQLException e) {
         e.printstacktrace ();
     }
}

We can track the source code, you can find that the most important thing is the docreatetable in two sentences:

Addcreatetablestatements (DatabaseType, Tableinfo, statements, Queriesafter, ifnotexists);

int STMTC = dostatements (Connection, "create", statements, False, 
          databasetype.iscreatetablereturnsnegative (), Databasetype.iscreatetablereturnszero ());

First look at the addcreatetablestatements implementation:

private static <t, id> void Addcreatetablestatements (DatabaseType databasetype, tableinfo<t, id> TableInfo, list<string> statements, List<string> Queriesafter, Boolean ifnotexists) throws SQLException {STRINGB
        Uilder sb = new StringBuilder (256);
        Sb.append ("CREATE TABLE");
        if (ifnotexists && databasetype.iscreateifnotexistssupported ()) {sb.append ("if not EXISTS"); Databasetype.appendescapedentityname (SB, Tableinfo.gettablename ());
        Add table name Sb.append ("(");
        ArrayList Additionalargs = new ArrayList ();
        ArrayList Statementsbefore = new ArrayList ();
        ArrayList statementsafter = new ArrayList ();
        Boolean-i = true; fieldtype[] i$ = Tableinfo.getfieldtypes ();

        Gets the properties of the table int arg = i$.length;
            for (int i$1 = 0; i$1 < arg; ++i$1) {FieldType FieldType = i$[i$1]; if (!fieldtype.isforeigncollection ()) {if (fiRST) {i = false; else {sb.append (",");
                The first parameter does not require ","} String columndefinition = Fieldtype.getcolumndefinition (); if (columndefinition = null) {Databasetype.appendcolumnarg (Tableinfo.gettablename (), SB, Fieldt
                Ype, Additionalargs, Statementsbefore, Statementsafter, Queriesafter);
                    else {databasetype.appendescapedentityname (SB, Fieldtype.getcolumnname ()); Sb.append ("). Append (ColumnDefinition). Append ("); Add column name}} databasetype.addprimarykeysql (Tableinfo.getfieldtypes (), Additi
        Onalargs, Statementsbefore, Statementsafter, Queriesafter); Databasetype.adduniquecombosql (Tableinfo.getfieldtypes (), Additionalargs, Statementsbefore, StatementsAfter,
        Queriesafter);

        Iterator var16 = Additionalargs.iterator (); while (Var16.hasnext () {String var15 = (string) var16.next ();
        Sb.append (","). Append (VAR15); } sb.append (")");
        Assemble the end Databasetype.appendcreatetablesuffix (SB);
        Statements.addall (Statementsbefore);
        Statements.add (Sb.tostring ());
        Statements.addall (Statementsafter);
        Addcreateindexstatements (DatabaseType, Tableinfo, statements, ifnotexists, false);
    Addcreateindexstatements (DatabaseType, Tableinfo, statements, ifnotexists, true); }

Here, we finally see some familiar words, those are the database of the original SQL statement, this function is mainly responsible for generating the SQL statement we want to execute. Then the dostatements executes the SQL statement:

private static int dostatements (databaseconnection connection, String label, collection<string> statements, Boolean ignoreerrors, Boolean returnsnegative, Boolean Expectingzero) throws SQLException {
    int stmtc = 0;
    for (Iterator i$ = Statements.iterator (); I$.hasnext (); ++stmtc) {
        String statement = (string) i$.next ();
        int ROWC = 0;
        Compiledstatement compiledstmt = null;

        COMPILEDSTMT = connection.compilestatement (statement, Statementtype.execute, Nofieldtypes,-1);
        ROWC = Compiledstmt.runexecute ();
        Logger.info ("executed {} Table statement changed {} rows: {}", label,                          
                     integer.valueof (ROWC), statement);

       ..
    return STMTC;
}
Related Article

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.