OrmLite是一个数据库操作辅助的开源框架,底层还是Sqlite。O-R-M是Object relational mapping(对象关系映射)的缩写,即业务实体对象与关系型数据库之间的映射。业务实体对象就是我们所说的model类,可以类比为Gson解析时的model类;关系型数据库可以理解为二维数据库,表的格式就如Excel,有行和列两个维度,sqlite就是二维的;映射:对象中的属性与数据库表中的字段一一对应。OrmLite直接操作业务对象,隐藏了数据库操作的细节,使我们不用通过sql语句与数据库打交道。
OrmLite通过Java注解的方式与数据库建立映射关系,在这里我以一个实例来进行说明,现在建立一个简单的数据库1607.db,并创建一张表Student来记录一个学生的名字,年龄,性别,学号等。
下面是最终的实现效果(能够正常的对数据库进行增删改查):
准备工作,先依赖类库:
dependencies {
compile 'com.j256.ormlite:ormlite-android:5.0'
}
一、首先,创建我们的业务实体对象,就是我们所说的model类,并通过注解的方式与数据库联系起来:
1.@DatabaseTable用来声明把此类作为数据库的表,可以在后面的括号中填入表名(不填的话就以类名作为表名)
2.@DatabaseField(columnName=”“)用来声明表的字段名,可以在后面的括号中设置字段的属性
package com.example.administrator.ormsqlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* Created by Administrator on 2016/10/14.
* 创建学生表
* 1,这个类就表示一张表,类中的属性表示字段
*,2,需要用注解来标明这个类就是一张数据表
* 3,需要用注解来标明属性为表中的字段
*/
@DatabaseTable //可以通过(tableName = "user")来改变表名
public class Student {
@DatabaseField //只有添加这个注释,才能把此属性添加到表中的字段
private String name;
@DatabaseField(generatedId = true) //generatedId = true 表示自增长的主键
private int id;
@DatabaseField
private String className;
@DatabaseField
private int userId;
@DatabaseField
private String sex;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
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;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
", className='" + className + '\'' +
", userId=" + userId +
", sex='" + sex + '\'' +
'}';
}
}
二、创建数据库
与Android中的数据库创建类似,使用OrmLite创建数据库需要我们创建一个OrmHelper继承OrmLiteSqliteOpenHelper,OrmLiteSqliteOpenHelper也有两个方法需要我们去实现,分别是onCreate和onUpgrade,负责数据库创建以及升级时的操作。
package com.example.administrator.ormsqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
/**
* Created by Administrator on 2016/10/14.
* 创建和维护数据库的类
*/
public class OrmHelper extends OrmLiteSqliteOpenHelper {
public static final String DB_NAME ="1607.db";
public static final int DB_VERSION = 1;
public OrmHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
//建表,和Gson类似,第二个参数即是业务实体类
try {
TableUtils.createTable(connectionSource,Student.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
//区分不同的版本做不同的更新
}
}
三、操作数据库
创建数据库之后就可以对数据库操作了,数据库的操作主要就是增删查改。OrmLite操作数据库的类是Dao,Dao相当于原生的SQLiteDatabase,一个Dao只能操作一张表。
1,插入操作
这些方法使用起来都比较简单,我们只需将自己的Bean传入到下列方法中即可
- create:插入一条数据
- createIfNotExists:如果不存在则插入
- createOrUpdate:如果存在则更新
2,查询数据
OrmLite为我提供了一系列的查询操作,方法很多,而且很多都是只看方法名就可以知道的,在这里介绍一下如何使用QueryBuilder进行复杂查找。
- 首先调用personDao.queryBuilder();获得该Dao下的QueryBuilder对象,
- 接下来设置QueryBuilder的查询条件,
- 最后通过QueryBuilder的query方法获得List对象
3,删除和修改数据
与查询操作类似,ORMLite同样为我们提供了一系列的方法,同时也提供了复杂删除,复杂更改的DeleteBuilder和UpdateBuilder,其用法与QueryBuilder相似。
package com.example.administrator.ormsqlite;
import android.content.Context;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import java.sql.SQLException;
import java.util.List;
/**
* Created by Administrator on 2016/10/14.
* 封装各种操作数据库的方法
*/
public class DBManager {
private final Dao dao;
/**
* 在构造中获取数据库的操作类
* @param context
* @throws SQLException
*/
public DBManager(Context context) throws SQLException {
OrmHelper ormHelper = new OrmHelper(context);
// SQLiteDatabase readableDatabase = ormHelper.getReadableDatabase(); //可以获取一个原生的数据库
//Dao相当于原生的SQLiteDatabase,可以操作数据库,一个Dao只能操作一张表
dao = ormHelper.getDao(Student.class);
}
/**
* 插入数据
* @param student
* @throws SQLException
*/
public void insertStudent(Student student) throws SQLException {
//在数据库中创建一条记录,作用与SQLiteDatabase.insert一样
dao.create(student);
}
/**
* 批量插入
* 不能使用循环一个一个的插入,因为这样会一直打开数据库、插入数据、
* 关闭数据库
* @param students
* @throws SQLException
*/
public void batchInsert(List<Student>students) throws SQLException {
dao.create(students);
}
/**
* 查询数据
* @return
* @throws SQLException
*/
public List<Student> getStudent() throws SQLException {
List<Student> list = dao.queryForAll();
return list;
}
/**
* 查询某个数据
* @return
* @throws SQLException
*/
public List<Student> queryGuanyu() throws SQLException {
//Eq是equals的缩写
//方法1
//List<Student> list = dao.queryForEq("name", "张飞");
//方法2
QueryBuilder queryBuilder = dao.queryBuilder();
// queryBuilder.offset(); //偏移量
// queryBuilder.limit(8l); //最多几行 offset + limit 做分页
// queryBuilder.orderBy("age",true);
queryBuilder.where().eq("name","关羽"); //多条件查询
List<Student> query = queryBuilder.query();//此方法相当于build,提交设置
return query;
}
/**
* 删除数据
* @param student
* @throws SQLException
*/
public void deleteStudent(Student student) throws SQLException {
//只看id
dao.delete(student);
}
/**
* 删除指定数据
* @throws SQLException
*/
public void deleteGuanyu() throws SQLException {
DeleteBuilder deleteBuilder = dao.deleteBuilder();
deleteBuilder.where().eq("name","关羽");
deleteBuilder.delete();
}
/**
* 修改数据
* @param student
* @throws SQLException
*/
public void updateStudent(Student student) throws SQLException {
student.setName("关羽");
dao.update(student);
}
/**
* 修改指定数据
* @throws SQLException
*/
public void updateGuanyu() throws SQLException {
UpdateBuilder updateBuilder = dao.updateBuilder();
updateBuilder.where().eq("name","关羽");
updateBuilder.updateColumnValue("sex","女");
updateBuilder.update();
}
}
四、在MainActivity中测试上面创建的数据库和对数据库操作的方法,并把数据显示到listview上,对应的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.administrator.ormsqlite.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/insert"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="插入数据" />
<Button
android:id="@+id/query"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="查询关羽"/>
<Button
android:id="@+id/delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="删除关羽"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/update"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="修改关羽"/>
<Button
android:id="@+id/insertAll"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="批量插入"/>
</LinearLayout>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
五、MainActivity中的代码,代码中没有什么新知识,该注释的都注释了,这里不再冗余:
package com.example.administrator.ormsqlite;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private DBManager dbManager;
private ListView list;
private List<Student> mStudents;
private MyAdapte myAdapte;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//把数据显示在listview上
myAdapte = new MyAdapte();
list.setAdapter(myAdapte);
//初始化DBManager
try {
dbManager = new DBManager(this);
} catch (SQLException e) {
e.printStackTrace();
}
//刚进来时查询所有的student
queryStudent();
//给listview设置点击监听和长按监听
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
try {
//单击删除该student
dbManager.deleteStudent(mStudents.get(i));
queryStudent();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
try {
//长按修改student
dbManager.updateStudent(mStudents.get(i));
queryStudent();
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
});
}
/**
* 初始化控件
*/
private void initView() {
findViewById(R.id.insert).setOnClickListener(this);
findViewById(R.id.delete).setOnClickListener(this);
findViewById(R.id.insert).setOnClickListener(this);
findViewById(R.id.insertAll).setOnClickListener(this);
findViewById(R.id.query).setOnClickListener(this);
list = (ListView) findViewById(R.id.list);
}
/**
* 查询所有的student
*/
public void queryStudent(){
try {
mStudents = dbManager.getStudent();
myAdapte.notifyDataSetChanged();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查询指定数据
*/
public void queryGuanyu(){
try {
mStudents = dbManager.queryGuanyu();
myAdapte.notifyDataSetChanged();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.insert: //插入一条数据
Student student = new Student();
student.setName("张飞");
student.setSex("男");
student.setUserId(123);
student.setClassName("1607");
try {
dbManager.insertStudent(student);
queryStudent();
} catch (SQLException e) {
e.printStackTrace();
}
break;
case R.id.delete: //删除指定数据(关羽)
try {
dbManager.deleteGuanyu();
queryStudent();
} catch (SQLException e) {
e.printStackTrace();
}
break;
case R.id.update: //修改指定数据(修改关羽的性别)
try {
dbManager.updateGuanyu();
queryStudent();
} catch (SQLException e) {
e.printStackTrace();
}
break;
case R.id.query: //查询指定数据(关羽)
queryGuanyu();
break;
case R.id.insertAll: //批量插入数据
List<Student> studnets = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Student stu = new Student();
stu.setName("刘备");
stu.setClassName("234");
stu.setUserId(i);
stu.setSex("男");
studnets.add(stu);
}
try {
dbManager.batchInsert(studnets);
queryStudent();
} catch (SQLException e) {
e.printStackTrace();
}
break;
}
}
/**
* ListView对应的适配器
*/
class MyAdapte extends BaseAdapter{
@Override
public int getCount() {
return mStudents == null ? 0 : mStudents.size();
}
@Override
public Object getItem(int i) {
return mStudents.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
TextView tv = new TextView(MainActivity.this);
tv.setTextSize(18);
tv.setText(mStudents.get(i).toString());
return tv;
}
}
}