Android ORM 框架 ORMLite

2016/09/28 Android

ORMLite这个框架是在ORM中被采用的比较多的一个。文档,实例,源码都比较多,维护也不错。

本文所介绍的版本是ORMLite。ormlite官网地址:www.ormlite.com

配置

添加依赖库:

compile 'com.j256.ormlite:ormlite-android:5.0'
compile 'com.j256.ormlite:ormlite-core:5.0'

使用

步骤一:创建类DatabaseHelper继承OrmLiteSqliteOpenHelper

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

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.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.zhy.zhy_ormlite.bean.Article;
import com.zhy.zhy_ormlite.bean.Student;
import com.zhy.zhy_ormlite.bean.User;

public  class DatabaseHelper extends OrmLiteSqliteOpenHelper
{
	private static final String DB_NAME = "sqlite-test.db";

	private Map<String, Dao> daos = new HashMap<String, Dao>();

	private DatabaseHelper(Context context)
	{
		super(context, DB_NAME, null, 4);
	}

	@Override
	public void onCreate(SQLiteDatabase database,
			ConnectionSource connectionSource)
	{
		try
		{
			TableUtils.createTable(connectionSource, User.class);
			TableUtils.createTable(connectionSource, Article.class);
			TableUtils.createTable(connectionSource, Student.class);
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase database,
			ConnectionSource connectionSource, int oldVersion, int newVersion)
	{
		try
		{
			TableUtils.dropTable(connectionSource, User.class, true);
			TableUtils.dropTable(connectionSource, Article.class, true);
			TableUtils.dropTable(connectionSource, Student.class, true);
			onCreate(database, connectionSource);
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	private static DatabaseHelper instance;

	/**
	 * 单例获取该Helper
	 * 
	 * @param context
	 * @return
	 */
	public static synchronized DatabaseHelper getHelper(Context context)
	{
    	// 如果是自定义Application,应采用以下语句
    	// context = MyApplication.getContext();
		context = context.getApplicationContext();
		if (instance == null)
		{
			synchronized (DatabaseHelper.class)
			{
				if (instance == null)
					instance = new DatabaseHelper(context);
			}
		}

		return instance;
	}

	public synchronized Dao getDao(Class clazz) throws SQLException
	{
		Dao dao = null;
		String className = clazz.getSimpleName();

		if (daos.containsKey(className))
		{
			dao = daos.get(className);
		}
		if (dao == null)
		{
			dao = super.getDao(clazz);
			daos.put(className, dao);
		}
		return dao;
	}

	/**
	 * 释放资源
	 */
	@Override
	public void close()
	{
		super.close();

		for (String key : daos.keySet())
		{
			Dao dao = daos.get(key);
			dao = null;
		}
	}

}

注:

  • 整个DatabaseHelper使用单例只对外公布出一个对象,保证app中只存在一个SQLite Connection 。
  • 我们对每个Bean创建一个XXXDao来处理当前Bean的数据库操作,当然真正去和数据库打交道的对象,通过上面代码中的getDao(T t)进行获取getDao为一个泛型方法,会根据传入Class对象进行创建Dao,并且使用一个Map来保持所有的Dao对象,只有第一次调用时才会去调用底层的getDao()。

步骤二:创建相应的Bean的Dao

import java.sql.SQLException;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.zhy.zhy_ormlite.bean.User;

public class UserDao
{
	private Context context;
	private Dao<User, Integer> userDaoOpe;
	private DatabaseHelper helper;

	public UserDao(Context context)
	{
		this.context = context;
		try
		{
			helper = DatabaseHelper.getHelper(context);
			userDaoOpe = helper.getDao(User.class);
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 增加一个用户
	 * @param user
	 */
	public void add(User user)
	{
		try
		{
			userDaoOpe.create(user);
		} catch (SQLException e)
		{
			e.printStackTrace();
		}

	}//...other operations


}

更多的操作如下:

// 增操作
// 在表中添加一条记录
public int create(T data) throws SQLException;
// 在表中添加一条记录,如果表不存在这条数据,根据设置的主键来判断是否存在
public T createIfNotExists(T data) throws SQLException;
// 在表中添加一条记录,如果存在则更新主键对应的一条记录,
public CreateOrUpdateStatus createOrUpdate(T data) throws SQLException;

// 删操作
// 根据传入实体删除
public int delete(T data) throws SQLException;
// 根据ID删除
public int deleteById(ID id) throws SQLException;
// 根据集合删除
public int delete(Collection<T> datas) throws SQLException;
// 根据id集合删除
public int deleteIds(Collection<ID> ids) throws SQLException;

// 改操作
// 根据传入的实体更新数据,ID为唯一标志
public int update(T data) throws SQLException;
// 更新ID,其他值不变
public int updateId(T data, ID newId) throws SQLException;

// 查操作
// 根据唯一标志id检索一条记录,如果id为
public T queryForId(ID id) throws SQLException;
// 查询匹配到的所有行中的第一个
public T queryForFirst(PreparedQuery<T> preparedQuery) throws SQLException;
// 返回表中所有条目,可导致大量数据导入内存,应该使用iterator方法来代替此方法
public List<T> queryForAll() throws SQLException;
// 查询指定字段value等于查询值的行: where fieldName = value
public List<T> queryForEq(String fieldName, Object value) throws SQLException;
// 匹配传入实体(字段不能为默认值,null,false,0,0.0等)的每个字段的值,每个条件进行and操作,返回的结果,可能导致SQL quote escaping
public List<T> queryForMatching(T matchObj) throws SQLException;
// 同上述方法,不会导致SQL quote escaping
public List<T> queryForMatchingArgs(T matchObj) throws SQLException;
// 根据传入的字段与value值的map匹配查询
public List<T> queryForFieldValues(Map<String, Object> fieldValues) throws SQLException;
// 根据传入的字段与value值的map匹配查询
public List<T> queryForFieldValuesArgs(Map<String, Object> fieldValues) throws SQLException;
// 查询与传入实体id相等的数据行
public T queryForSameId(T data) throws SQLException;
// 更高级的查询可以使用queryBuilder
dao.queryBuilder().orderBy("id", true).query();

步骤三:定义实体类Bean,代表一张表

import com.j256.ormlite.field.DatabaseField;  
import com.j256.ormlite.table.DatabaseTable;  
  
@DatabaseTable(tableName = "tb_user")  
public class User   
{  
    @DatabaseField(generatedId = true)  
    private int id;  
    @DatabaseField(columnName = "name")  
    private String name;  
    
    public User()  
    {  
    }  
  
    public int getId()  
    {  
        return id;  
    }  
  
    public void setId(int id)  
    {  
        this.id = id;  
    }  
  
    public String getName()  
    {  
        return name;  
    }  
  
    public void setName(String name)  
    {  
        this.name = name;  
    }  
  
    @Override  
    public String toString()  
    {  
        return "User [id=" + id + ", name=" + name   
                + "]";  
    }  
      
}  

ormLite封装后给Android原先的sqllite的操作方便许多。熟悉掌握此框架,可以给Android项目开发带来很大的方便。

Search

    Table of Contents