首页 > 代码库 > 【安卓笔记】ormlite入门

【安卓笔记】ormlite入门

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的代码高亮好难看

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

【安卓笔记】ormlite入门