OrmLite-android入门体验


入门体验

OrmLite 是一个轻量级的ORM(Object Relational Mapping)数据库工具,方便持久化java对象到数据库

1. 使用准备

使用androidADT创建android项目,如果使用androidStudio,在使用OrmLiteConfigUtil配置时会有麻烦,也可以不配置,后面会有介绍。下载[jar][1]选择ormlite-android和ormlite-core。

2. 创建测试表

OrmLite在每个类的顶部使用@DatabaseTable标识一个表,使用@DatabaseField标识每个字段。需要注意的是OrmLite需要一个空的构造函数。示例如下:

public class SimpleData {

    // 设置id自增长
    @DatabaseField(generatedId = true)
    int id;
    @DatabaseField(index = true)
    String string;
    @DatabaseField
    long millis;
    @DatabaseField
    Date date;
    @DatabaseField
    boolean even;

    SimpleData() {
    }
}

3. 实现DatabaseHelper

自定义的DatabaseHelper需要继承OrmLiteSqliteOpenHelper,和继承SQLiteOpenHelper的方法一样,需要实现onCreate和onUpgrade。同时可以提供DAO的get方法方便其他类使用。示例如下:

public class DatabaseHelper  extends OrmLiteSqliteOpenHelper {
    private static final String DATABASE_NAME = "helloAndroid.db";
    private static final int DATABASE_VERSION = 1;

    private Dao<SimpleData, Integer> simpleDao = null;
    private RuntimeExceptionDao<SimpleData, Integer> simpleRuntimeDao = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
        try {
            Log.i(DatabaseHelper.class.getName(), "onCreate");
            TableUtils.createTable(connectionSource, SimpleData.class);
        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            Log.i(DatabaseHelper.class.getName(), "onUpgrade");
            TableUtils.dropTable(connectionSource, SimpleData.class, true);
            onCreate(db, connectionSource);
        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
            throw new RuntimeException(e);
        }
    }

    public Dao<SimpleData, Integer> getDao() throws SQLException {
        if (simpleDao == null) {
            simpleDao = getDao(SimpleData.class);
        }
        return simpleDao;
    }

    public RuntimeExceptionDao<SimpleData, Integer> getSimpleDataDao() {
        if (simpleRuntimeDao == null) {
            simpleRuntimeDao = getRuntimeExceptionDao(SimpleData.class);
        }
        return simpleRuntimeDao;
    }

    @Override
    public void close() {
        super.close();
        simpleDao = null;
        simpleRuntimeDao = null;
    }
}

如果想提升应用启动速度,减少垃圾回收,那么不使用注解也是可行的,只是需要稍微配置下即可。

1、生成配置文件

实现一个OrmLiteConfigUtil生成ormlite_config.txt文件。需要注意的是,需要使用java方法生成这个配置文件。

public class DatabaseConfigUtil extends OrmLiteConfigUtil {
    private static final Class<?>[] classes = new Class[] {
        SimpleData.class,
        };
    public static void main(String[] args) throws SQLException, IOException {
        writeConfigFile("ormlite_config.txt");
    }
}

直接右键运行Run As -> Java Application是不可行,需要修改java运行配置。
修改jre为1.5 或1.6。我的是java1.7,因此需要修改

20141125184015.jpg

然后在classpath栏删除Android bootstrap

20141125184304.jpg

然后在android项目的res目录添加一个空的raw文件夹,执行main方法,控制台显示类似信息,则表示生成成功。

Writing configurations to E:\workspace\androidADT\ORMLite\.\res\raw\ormlite_config.txt
Done.

接着修改DatabaseHelper类的构造函数

public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
    }

配置完成。

4. 使用

官方提供了OrmLiteBaseActivity、OrmLiteBaseListActivity、OrmLiteBaseService等类可以直接继承使用。

public class MainActivity extends OrmLiteBaseActivity<DatabaseHelper> {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        doSampleDatabaseStuff("onCreate", tv);
        setContentView(tv);
    }
    private void doSampleDatabaseStuff(String action, TextView tv) {
        RuntimeExceptionDao<SimpleData, Integer> simpleDao = getHelper().getSimpleDataDao();
        List<SimpleData> list = simpleDao.queryForAll();
        //TODO 
    }
}

但是如果继承ActionBarActivity之类的类,或是自己实现的类。那么在代码的开头需要调用

OpenHelperManager.getHelper(Context context, Class openHelperClass)

在使用完毕释放掉

OpenHelperManager.release()

示例如下:

private DatabaseHelper databaseHelper = null;
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
         }
    }
    private DBHelper getHelper() {
        if (databaseHelper == null) {
            databaseHelper =
            OpenHelperManager.getHelper(this, DatabaseHelper.class);
        }
        return databaseHelper;
    }

需要注意的是,如果在子线程中如果调用了 OpenHelperManager.getHelper()
需要在适当的时候释放掉release()
示例代码地址 [点我 :)][2]
参考文档和示例
http://ormlite.com/docs/ormlite.pdf
http://ormlite.com/android/examples/
[1]: http://ormlite.com/releases/
[2]: http://download.csdn.net/download/mnb123jhg/8197735

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,702评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,506评论 19 139
  • 为天地立心,为生民立命,为往圣继绝学,为万世开太平 这句话是北宋关学学派创始人说的,被冯友兰称为“横渠四句”。这也...
    漫书见贤阅读 3,196评论 0 0
  • zcs舌间音 舌间前音和舌间后音的区别 Z:舌尖轻轻抵住下齿背,软腭上升 C :舌尖轻轻抵住下齿背,软腭上升 S:...
    fa8d2ce27904阅读 2,967评论 0 0
  • 分手是种勇气,生活还在继续。每一段都只是生命中的一个小插曲,而这也将预示着你的真正王子即将出现。 不必为已过去的事...
    龙山启后阅读 2,953评论 0 0