【安卓笔记】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();
}
}
}
是不是很简单?那就赶紧用起来吧!
ps:markdown的代码高亮好难看
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。