OrmLite是一个轻量级的ORM框架,面向JAVA语言。也是时下流行的Android的ORM框架之一。在Android中使用Sqlite数据,如果又不想写SQL,OrmLite或许是个不错的选择。
使用OrmLite,首先要在gradle配置依赖 compile 'com.j256.ormlite:ormlite-android:4.48'
也可以去ormlite官网下载查看文档 http://ormlite.com/
1.表创建
然后要要创建一个实体类,对应表结构。OrmLite提供了两个注解,@DatabaseField 代表表列名,@DatabaseTable 表名 tableName值为数据库中表的真实名称。下列的User类必须有一个无参数的构造函数。
需要指定一个字段为唯一标志,必须为int, Integer ,long, Long, Uuid类型
数据库中的记录通过定义为唯一的特殊字段成为唯一标识。记录不是必须有唯一标识字段当时很多DAO操作(更新、删除、刷新)都需要一个唯一标识字段。这个标识要么用户提供要么数据库自动生成。标识字段有表中唯一的值并且如果你用DAO根据id查询、删除、刷新或者更新指定行的时候他们必须存在。为了配置一个成员变量作为标识成员,你应该使用下面三个设置之一(而且必须使用一个):@DatabaseField: id, generatedId, generatedIdSequence 。
@DatabaseField(id = true)指定哪个字段为主键
@DatabaseField(generatedId = true)自动增加的ID
@DatabaseField(generatedIdSequence = true) 设置序列名来匹配已经存在的schema,你可以使用generatedIdSequence指定序列名的值。
这样才可以使用ID来做删除,修改,查询等操作。否则调用相关方法抛出
Cannot query-for-id with class xxx.xxx.xxx.User because it doesn't have an id field相关异常。
@DatabaseTable(tableName = "t_user")
public class User {
@DatabaseField(generatedId =true)
private int id;
@DatabaseField
private String name;
public User(int id, String name) {
this.name = name;
this.id = id;
}
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Android中使用Sqlite需要继承自SQLiteOpenHelper,要使用ormlite需要继承OrmLiteSqliteOpenHelper,来实现一些创建数据库,创建表,更新表的操作。TableUtils是个工具类,主要提供表的创建,表的移除等操作。
public class DbHelper extends OrmLiteSqliteOpenHelper {
private DbHelper(Context context) {
//参数:上下文,数据库名称,cursor factory,数据库版本.
super(context, "test.db", null, 1);
}
//第一次操作数据库时候,被调用
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, User.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
//当数据库版本升级的时候,被调用
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
try {
//这里只是粗暴的移除了旧表,新建新表,这样会导致数据丢失,现实一般不这么做
TableUtils.dropTable(connectionSource, User.class, true);
onCreate(sqLiteDatabase, connectionSource);
} catch (SQLException e) {Orm
e.printStackTrace();
}
}
//实现一个单例返回DbHelper实例
private static DbHelper helper;
public static DbHelper getHelper(Context context) {
if (helper == null) {
helper = new DbHelper(context);
}
return helper;
}
}
2.表的增删改查
首先通过上述的单例类获取一个OrmLiteSqliteOpenHelper的实例,该类中有个getDao(Class clazz)方法可以获取到对应实体的dao对象,参数clazz为表对应的实体的class对象,例如User.class 。
通过getDao返回一个Dao的实例,dao中有增删改查的方法。
从helper获取一个dao的实例
private Dao userDao;
public UserDao() {
init();
}
private void init() {
DbHelper dbHelper = DbHelper.getHelper(ContextProvider.getApplicationContext());
try {
userDao = dbHelper.getDao(User.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
在表中添加一条记录
public int create(T data) throws SQLException;
在表中添加一条记录,如果表不存在这条数据,根据设置的主键来判断是否存在
public T createIfNotExists(T data) throws SQLException;
在表中添加一条记录,如果存在则更新主键对应的一条记录,
public CreateOrUpdateStatus createOrUpdate(T data) throws SQLException;
User user = new User();
userDao.create(user);
userDao.createOrUpdate(user);
userDao.createIfNotExists(user);
删除
根据传入实体删除
public int delete(T data) throws SQLException;
根据ID删除
public int deleteById(ID id) throws SQLException;
根据集合删除
public int delete(Collection datas) throws SQLException;
根据id集合删除
public int deleteIds(Collection ids) throws SQLException;
userDao.deleteIds(ids);
userDao.deleteById(id);
userDao.delete(user);
userDao.delete(list);
更新
//根据传入的实体更新数据,ID为唯一标志
public int update(T data) throws SQLException;
//更新ID,其他值不变
public int updateId(T data, ID newId) throws SQLException;
mDao.update(new User(1, "update"));
//更新id指定行的数据
mDao.updateId(new User(mId, mName), 10000);
//把当前的行id更新为10000
查询
根据唯一标志id检索一条记录,如果id为
public T queryForId(ID id) throws SQLException;
查询匹配到的所有行中的第一个
public T queryForFirst(PreparedQuery preparedQuery) throws SQLException;
返回表中所有条目,可导致大量数据导入内存,应该使用iterator方法来代替此方法
public List queryForAll() throws SQLException;
查询指定字段value等于查询值的行: where fieldName = value
public List queryForEq(String fieldName, Object value) throws SQLException;
匹配传入实体(字段不能为默认值,null,false,0,0.0等)的每个字段的值,每个条件进行and操作,返回的结果,可能导致SQL quote escaping
public List queryForMatching(T matchObj) throws SQLException;
同上述方法,不会导致SQL quote escaping
public List queryForMatchingArgs(T matchObj) throws SQLException;
根据传入的字段与value值的map匹配查询
public List queryForFieldValues(Map fieldValues) throws SQLException;
根据传入的字段与value值的map匹配查询
public List queryForFieldValuesArgs(Map fieldValues) throws SQLException;
查询与传入实体id相等的数据行
public T queryForSameId(T data) throws SQLException;
mDao.queryForAll();
mDao.queryForId(mId);