【安卓筆記】ormlite入門

來源:互聯網
上載者:User

標籤:std   pretty   優勢   seh   try catch   http   ring   最佳實務   pre   

ps:寫這篇文章的目的是嘗試下新的markdown編輯器哈哈

簡單介紹

ORMLite provides a lightweight Object Relational Mapping between Java classes and SQL databases. There are certainly more mature ORMs which provide this functionality including Hibernate and iBatis. However, the author wanted a simple yet powerful wrapper around the JDBC functions, and Hibernate and iBatis are significantly more complicated with many dependencies.

Ormlite和GreenDao都是android平台經常使用的orm架構。兩者各有優勢,ormlite勝在簡單,可是其基於註解反射。速度比不上greendao。
ormlite官網:http://ormlite.com/

注:ormlite不僅能夠用於android平台,也能夠結合jdbc使用的

怎樣使用

  • 首先你須要加入ormlite庫的依賴到build.gradle中:

dependencies {
compile ‘com.j256.ormlite:ormlite-core:4.48’
compile ‘com.j256.ormlite:ormlite-android:4.48’
}

  • 建立一個bean映射資料庫中相應的table

比方我這裡想建立一個手機黑名單資料表,表名叫black,表相應欄位例如以下:

id name number
主鍵、自增長 名稱 號碼

假設使用SqliteOpenHelper的話,須要在onCreate中運行sql語句建立table。可是使用ormlite只須要建立以下這個bean。

import com.j256.ormlite.field.DatabaseField;import com.j256.ormlite.table.DatabaseTable;/** * Created by Rowandjj on 2015/5/26. */@DatabaseTable(tableName = "black")public class BlackEntity//映射到資料庫就是一個名為black的表{    @DatabaseField(generatedId = true)    public int id;//使用DatabaseField註解表明這是一個欄位    @DatabaseField    public String name;    @DatabaseField    public String number;    public BlackEntity(){}    public BlackEntity(String name, String number)    {        this.name = name;        this.number = number;    }    @Override    public String toString()    {        return "BlackEntity{" +                "id=" + id +                ", name=‘" + name + ‘\‘‘ +                ", number=‘" + number + ‘\‘‘ +                ‘}‘;    }    public String getName()    {        return name;    }    public void setName(String name)    {        this.name = name;    }    public String getNumber()    {        return number;    }    public void setNumber(String number)    {        this.number = number;    }}

很多其它註解如外鍵等等參見文檔

  • 繼承OrmliteSqliteOpenHelper。並複寫相關方法
    最基本的是onCreate和onUpgrade方法。
import android.content.Context;import android.database.sqlite.SQLiteDatabase;import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;import com.j256.ormlite.dao.Dao;import com.j256.ormlite.dao.RuntimeExceptionDao;import com.j256.ormlite.support.ConnectionSource;import com.j256.ormlite.table.TableUtils;import com.taobao.easysafe.constants.DBConfig;import java.sql.SQLException;/** * Created by Rowandjj on 2015/5/26. */public class ListDBHelper extends OrmLiteSqliteOpenHelper{    /**黑名單*/    private Dao<BlackEntity, Integer> mBlackDao;    private RuntimeExceptionDao<BlackEntity, Integer> mRuntimeBlackDao;    public ListDBHelper(Context context)    {          super(context, DBConfig.BW_LIST/*資料庫名稱*/, null, 1);    }    @Override    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource)    {        try        {            TableUtils.createTable(connectionSource, BlackEntity.class);        } catch (SQLException e)        {            e.printStackTrace();        }    }    @Override    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)    {        try         {               TableUtils.dropTable(connectionSource,BlackEntity.class);               onCreate(database, connectionSource);         }catch(Exception e)         {               e.printStackTrace();         }    }    public Dao<BlackEntity, Integer> getBlackDao() throws SQLException    {        if (mBlackDao == null)        {            mBlackDao = getDao(BlackEntity.class);        }        return mBlackDao;    }    public RuntimeExceptionDao<BlackEntity, Integer> getRuntimeExceptionBlackDao()    {        if(mRuntimeBlackDao == null)        {            mRuntimeBlackDao = getRuntimeExceptionDao(BlackEntity.class);        }        return mRuntimeBlackDao;    }}

ormlite提供了TableUtils類幫我們運行建立/銷毀表的功能。

  • 運行CRUD操作
    要想運行CRUD操作,得首先拿到Dao,即調用ListDBHelper的getBlackDao或getRuntimeExceptionBlackDao方法,這兩個方法的差別是getRuntimeExceptionBlackDao不須要你寫一堆try catch,當出現故障時它會自己主動拋出異常。
    如今問題來了,怎樣得到ListDBHelper執行個體呢?直接new嗎??當然不!

    資料庫連接是稀有資源,不應該建立多個執行個體。

    Ormlite提供了OpenHelperManager類幫我們建立執行個體,調用靜態getHelper就可以:

ListDBHelper mDBHelper;private ListDBHelper getHelper(){     if (mDBHelper == null)     {         mDBHelper = OpenHelperManager.getHelper(this/*Context執行個體*/, ListDBHelper.class);     }     return mDBHelper;}

ListDBHelper使用完記得釋放,最佳實務是放到Activity的onDestroy中:

@Override    protected void onDestroy()    {        super.onDestroy();        if (mDBHelper != null)        {            OpenHelperManager.releaseHelper();            mDBHelper = null;        }    }

有了mDBHelper執行個體後,我們就能夠拿到DAO。並調用其CRUD方法:
增:

private void addToBlack(ContactInfo info){        if (info != null && info.getName() != null && info.getNumber() != null)        {            BlackEntity entity = new BlackEntity(info.getName(), info.getNumber());            getHelper().getRuntimeExceptionBlackDao().create(entity);        }}

查:

 private List<BlackEntity> queryBlack()    {        return getHelper().getRuntimeExceptionBlackDao().queryForAll();    }

刪:
dao提供了一系列的delete方法。可參考文檔使用,這裡介紹一種更強大的DeleteBuilder,它能夠添加where條件,並且api是builder模式,不停的點點點,全然停不下來~haha,當然嘍,不不過DeleteBuilder,還有QueryBuilder、UpdateBuilder等

private void removeBlack(ContactInfo info)    {        int result = -1;        if(info != null)        {            Logger.d("TAG", info.getName() + "," + info.getNumber());            try            {                DeleteBuilder builder = getHelper().getRuntimeExceptionBlackDao().deleteBuilder();                builder.where().eq("name",info.getName()).and().eq("number",info.getNumber());                result = builder.delete();            } catch (SQLException e)            {                e.printStackTrace();            }        }    }

是不是非常easy?那就趕緊用起來吧!

ps:markdown的代碼高亮好難看

【安卓筆記】ormlite入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.