1. 程式人生 > >【安卓筆記】ormlite入門

【安卓筆記】ormlite入門

base 字段 tool uil nali ews 文檔 實例 自增

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入門