【安卓筆記】ormlite入門

rowandjj發表於2015-06-02

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();
            }
        }
    }

是不是很簡單?那就趕緊用起來吧!

ps:markdown的程式碼高亮好難看

相關文章