一般的项目中,Android自身提供的SQLite数据库,可以满足轻量级的数据存储应用,但是,只要是存储模型稍微复杂的项目,以及数据结构模型复杂的应用,就很难再用SQLite支撑整个项目的数据存储。何况,使用SQLite编写的代码,代码后续维护和管理不容易,所以,上规模的项目中,很有必要引入一种更好用、对开发者更友好的第三方ORM数据库框架:ORMlite。
ORMLite官方的简介说:“Object Relational Mapping Lite (ORM Lite) provides some simple, lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages.”。
ORMLite是对象关系映射(Object Relational Mapping)数据库的一种轻量级SQL数据库的开发包(packages)。提供简单易用的DAO。
将上面的两个jar包下载后放到Android工程项目中的libs包中,如图所示:
以上完成后,ORMLite开发环境搭建就完成了,接下来就可以使用了。
首先需要创建和定义一张ORMLite用以存储的数据库表,这个表,用Java的一个类实现,例如User.java:
package zhangphil.ormlitetest.database;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "users")
public class User {
public final static String USER_ID = "user_id";
public final static String NAME = "name";
public final static String AGE = "age";
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
// @DatabaseField(generatedId = true)
// public int id;
@DatabaseField(id = true, columnName = USER_ID)
public int user_id;
@DatabaseField(columnName = NAME)
public String name;
@DatabaseField(columnName = AGE)
public int age;
public int getUserId() {
return user_id;
}
public void setUserId(int uid) {
this.user_id = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "user_id:" + user_id + " 姓名:" + name + " 年龄:" + age;
}
}
上面的这个Java类User中开始一段代码:
@DatabaseTable(tableName = "users")
此代码声明了User类中定义的数据模型,将存储在数据库表“users”中。换句话说,数据库表users中,存储的数据单元也即是类User中定义的数据模型。
其中:
@DatabaseField(columnName = “xxx”)
xxx 表示此数据字段在数据库表中的列名。
DatabaseField中,若设定id=true,则声明此id为主键。
ORMLite的数据库表定义可设置的参数比较多,这点可以参考官方文档。剩余的就是创建ORMLite数据库,和SQLite类似。ORMLite查插删改主要通过DAO。
现在给出一个简单的代码加以说:
定义一个ORMLite数据库表User.java,假设该User表存储用户的id、名字、年龄信息:
package zhangphil.ormlitetest.database;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "users")
public class User {
public final static String USER_ID = "user_id";
public final static String NAME = "name";
public final static String AGE = "age";
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
// @DatabaseField(generatedId = true)
// public int id;
@DatabaseField(id = true, columnName = USER_ID)
public int user_id;
@DatabaseField(columnName = NAME)
public String name;
@DatabaseField(columnName = AGE)
public int age;
public int getUserId() {
return user_id;
}
public void setUserId(int uid) {
this.user_id = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "user_id:" + user_id + " 姓名:" + name + " 年龄:" + age;
}
}
创建ORMLite数据库管理工具类ORMLiteDatabaseHelper.java:
package zhangphil.ormlitetest.database;
import java.sql.SQLException;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
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;
public class ORMLiteDatabaseHelper extends OrmLiteSqliteOpenHelper {
private static ORMLiteDatabaseHelper mDatabaseHelper = null;
private Dao<User, Integer> mUserDao = null;
private final static String DataBase_NAME = "ormlite.db";
private final static int DataBase_VERSION = 1;
public ORMLiteDatabaseHelper(Context context, String databaseName,
CursorFactory factory, int databaseVersion) {
super(context, DataBase_NAME, factory, DataBase_VERSION);
}
public static ORMLiteDatabaseHelper getInstance(Context context) {
if (mDatabaseHelper == null) {
mDatabaseHelper = new ORMLiteDatabaseHelper(context, DataBase_NAME,
null, DataBase_VERSION);
}
return mDatabaseHelper;
}
@Override
public void onCreate(SQLiteDatabase arg0, ConnectionSource connectionSource) {
Log.d(this.getClass().getName(), "ORMLite数据库 -> onCreate");
try {
TableUtils.createTableIfNotExists(connectionSource, User.class);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource arg1,
int arg2, int arg3) {
Log.i(this.getClass().getName(), "数据库 -> onUpgrade");
try {
// 删除旧的数据库表。
TableUtils.dropTable(connectionSource, User.class, true);
// 重新创建新版的数据库。
onCreate(database, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 每一个数据库中的表,要有一个获得Dao的方法。 可以使用一种更通用的模板方法如:
*
* public Dao<Class, Integer> getORMLiteDao(Class cls) throws SQLException {
* if (dao == null) { dao = getDao(cls); }
*
* return dao; }
*/
public Dao<User, Integer> getUserDao() {
if (mUserDao == null) {
try {
mUserDao = getDao(User.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return mUserDao;
}
@Override
public void close() {
super.close();
mUserDao = null;
}
}
然后就可以在自己的应用中直接使用:
package zhangphil.ormlitetest;
import java.sql.SQLException;
import java.util.List;
import java.util.Random;
import com.j256.ormlite.dao.Dao;
import zhangphil.ormlitetest.database.ORMLiteDatabaseHelper;
import zhangphil.ormlitetest.database.User;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity {
private Dao<User, Integer> mUserDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ORMLiteDatabaseHelper mDatabaseHelper = ORMLiteDatabaseHelper
.getInstance(this);
mUserDao = mDatabaseHelper.getUserDao();
Random rand = new Random();
for (int i = 0; i < 3; i++) {
User user = new User();
user.setUserId(i);
user.setName("name" + i);
// 生成随机测试的年龄。
user.setAge(rand.nextInt(100));
try {
mUserDao.createOrUpdate(user);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Override
public void onStart() {
super.onStart();
// 全局查询
try {
List<User> users = mUserDao.queryForAll();
for (User u : users) {
Toast.makeText(this, u.toString(), Toast.LENGTH_SHORT).show();
}
} catch (SQLException e) {
e.printStackTrace();
}
// 条件查询QueryBuilder
// 假设我们给定一个用户的id=1
int uid = 1;
try {
List<User> users = mUserDao.queryBuilder().where()
.eq(User.USER_ID, uid).query();
for (User u : users) {
Toast.makeText(this, "查询结果 : " + u.toString(),
Toast.LENGTH_SHORT).show();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}