OrmLite数据库框架
常用ORM框架有:
--OrmLite 使用注解,使用简单
--GreenDAO 自动生成代码,性能高
--SugarORM
--Active Android
--Realm
下载OrmLite开发包
http://ormlite.com 下载ormlite-android-x.xx.jar和ormlite-core-x.xx.jar
导入工程
复制到libs,选中->右键->Add As Library
使用
1、创建实体类,添加注解
表前添加
@DatabaseTable[tableName="tb_student"]
字段前添加
@DatabaseField(generatedId=true)
@DatabaseField(columnName="name",dataType=DataType.STRING,canBeNull=false]
@DatabaseField
2、创建帮助类,继承OrmLiteSqliteOpenHelper
实现单例模式:
public static synchronized DatabaseHelper getInstance(Context context){
if(sInstance==null){
sInstance=new DatabaseHelper(context);
}
return sInstance;
}
onCreate方法:
TableUtils.createTable(connectionSource,Student.class);//Student为带注解的实体类名
onUpgrade方法:
TableUtils.dropTable(connectionSrouce,Student.class,true);//true 忽略错误
onCreate(sqlLiteDatabase,connectionSrouce);//调用onCreate方法重新创建表
3、获得对应表的Dao类
DatabaseHelper helper=DatabaseHelper.getInstance(this);//获得DatabaseHelper实例
Dao<Student,Ingteger> stuDao=helper.getDao(Student.class);//获得表的DAO,泛型:类型、编号
4、执行增删改查操作
插入数据:
Student stu1=new Student("张三",33,"13300001111");
Student stu2=new Student("李四",23,"13300002222");
Student stu3=new Student("王五,21,"13300003333");
stuDao.create(stu1);
stuDao.createOrUpdate(stu2);
stuDao.createIfNoExists(stu3);
查询数据:
List<Student> students1=stuDao.queryForAll();
List<Student> students2=stuDao.queryForId(3);
List<Student> students3=stuDao.queryForEq("name","李四");
更新数据:
UpdateBuilder update=stuDao.updateBuilder();
update.setWhere(update.where().eq("phone","13300002222").and().gt("age",20));//gt:大于,lt:小于
update.updateColumnValue("name","小李子");
update.updateColumnValue("phone","13899998888");
update.update();
或
stuDao.updateRaw("update tb_student set name='小张',phone='13844448888' where id=?","1");
删除数据:
stuDao.deleteById(1);
一对多关系
Student类
...
@DatabaseField(column="school_id",foreign=true,foreignAutoRefresh=true)
private School school;
School类
...
@ForeignCollectionField
private Collection<Student> students;
事务
批量数据操作时,大大提高操作效率。事务是一个整体,要么全执行,要么全不执行。
如果把1000条数据放到一个事务里插入数据库中。将一次性插入;一条出错整体不能插入。
DatabaseHelper helper=DatabaseHelper.getInstance(this);
final Dao<Student,Integer> stuDao=helper.getDao(Student.class);
final Student stu=new Student("测试事务",18,"110",new Shool("清华大学","北京"));
TransactionManager.callInTransaction(
helper.getConnectionSource(),
new Callable<Void>(){
@Override
public Void call() throws Exception{
for(int i=0;i<20;i++){
stuDao.create(stu);
if(i==10){
throw new SQLException("test");
}
}
return null;
}
});
Okio框架
导包
module,右键->Open module settings ->dependencies->添加,搜索"okio",选择com.squareup.okio:okio:x.x.x