前言:近期为了做一个项目,所以特地去了解了一些开源框架,对这些开源框架了解也是浅层的,并没有深入。以前学习都是写在印象笔记里面,会写的比较随意。写在博客里,会更加认真对待,边写边加深知识点的理解。
ps:本篇内容较多,篇幅较长,要耐着性子看下去
开源链接:https://github.com/greenrobot/greenDAO
什么是ORM
学习之前首先要了解什么是ORM。ORM(Object Relational Mapping),对象关系映射。就是对象模型表示的对象映射到基于SQL的关系型数据库结构中。
通俗的说就是,将对象转换到SQL中存储。
例如:
public class Customer{
private Integer id;
private String name;
private Integer age;
private String des;
}
对象在数据库中的存储情况如下:
Customers表
根据上表可知,每个对象就是一条记录,每个属性就是 一列。
greenDAO
DAO(data access object)数据访问对象,就是访问数据库的接口。
greenDAO 是一个将对象映射到 SQLite 数据库中的轻量且快速的 ORM 解决方案。
设计目标:
- 一个精简的库
- 性能最大化
- 内存开销最小化
- 易于使用的 APIs
- 对 Android 进行高度优化
优点:
- 效率高,插入和更新的速度是SQLite的两倍
- 文件小(<100k)占用很少的内存
- 操作实体灵活
使用方法
greenDAO的使用较为复杂:
1.在root build.gradle中添加:
buildscript {
repositories {
jcenter()
mavenCentral() //add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0' // add plugin
}
}
2.在app build.gradle中添加:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
dependencies {
compile'org.greenrobot:greendao:3.0.1'
compile'org.greenrobot:greendao-generator:3.0.0'
}
创建实体类
@Entity
public class User {
@Id //主键,默认会自增
private Long Id;
private String name;
@Transient
private int tempUsageCount; // not persisted
@Transient,表明这个字段不会被写入数据库,只是作为一个普通的java类字段,用来临时存储数据的,不会被持久化
点击build->make project 会自动生成三个类,User类也会自动扩展
package com.example.greendaotest;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Transient;
import org.greenrobot.greendao.annotation.Generated;
/**
* Created by rhm on 2017/6/3.
*/
@Entity
public class User {
@org.greenrobot.greendao.annotation.Id //主键,默认会自增
private Long Id;
private String name;
@Transient
private int tempUsageCount; // not persisted
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return this.Id;
}
public void setId(Long Id) {
this.Id = Id;
}
@Generated(hash = 690585871)
public User(Long Id, String name) {
this.Id = Id;
this.name = name;
}
@Generated(hash = 586692638)
public User() {
}
}
如图,IDE会自动生成另一个包存放新生成的三个类
我们也可以指定生成包的名字,在app build.gradle中
greendao {
schemaVersion 1 //版本号
daoPackage 'com.example.greendaodtext.greendao'//生成三个类的包
targetGenDir 'src/main/java' //路径
}
3.创建使用greenDAO的方法类,这样结构更清晰,有助于我们复用,在这里我们创建了数据库,为了保证他的唯一性,我们使用了单例模式,因为在创建数据库的时候需要使用的Context,所以要先自己建立一个Application:
//获取全局的Context
public class MyApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public static Context getContext() {
return context;
}
}
别忘了在Manifest中声明:
<application
android:name=".MyApplication"
..../>
创建数据库的关键代码:
//创建数据库
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(MyApplication.getContext(), "user-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
master = new DaoMaster(db);
session = master.newSession();
//创建数据库,需要使用单例模式,保证唯一的一个数据库。
public class GreenDaoManager {
private DaoMaster master;
private DaoSession session;
private static GreenDaoManager instance;
//创建一个数据库
private GreenDaoManager() {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(MyApplication.getContext(), "user-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
master = new DaoMaster(db);
session = master.newSession();
}
//获得唯一的实例
public static GreenDaoManager getInstance() {
if (instance == null) {
instance = new GreenDaoManager();
}
return instance;
}
public DaoMaster getMaster() {
return master;
}
public DaoSession getSession() {
return session;
}
}
通过上面的操作类,我们可以发现,使用greenDao不需要创建表(create table),因为它会自动帮我们创建。在使用greenDAO进行数据库的增删改查操作之前,了解下DaoMaster,DaoSession,Dao的定义。
DaoMaster:
是greenDAO的入口点,保存数据对象和管理特殊模式的Dao类。能创建,删除表。其中的内部类OpenHelper,DevOpenHelper是通过SQLiteOpenHelper的实现在SQLite database中的操作。
DaoSession
管理所有可用的Dao类,提供了insert,load,update,refresh,delete等方法。
Dao
每个实体都对应一个Dao,它比DaoSession多了count,loadAll,insertInTX的方法。
4.在MainActivity中的使用,要通过getSession()获得所有实体的方法:
UserDao userDao = GreenDaoManager.getInstance().getmDaoSession().getUserDao();
下面增删改查的代码列出来:
//插入
public void insert(Long id, String name) {
User user = new User(id, name);
UserDao userDao = GreenDaoManager.getInstance().getSession().getUserDao();
userDao.insert(user);
}
//查询
public void query() {
UserDao userDao = GreenDaoManager.getInstance().getSession().getUserDao();
userList.clear();
userList.addAll(userDao.loadAll());
adapter.notifyDataSetChanged();
}
//删除
public void delete(String name) {
UserDao userDao = GreenDaoManager.getInstance().getSession().getUserDao();
//当有多个相同名字的,一同删除
List<User> findUser = userDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().list();
if (findUser != null) {
for (int i = 0; i < findUser.size(); i++) {
//通过主键删除
userDao.deleteByKey(findUser.get(i).getId());
}
}
}
public void update(String preName, String newName) {
UserDao userDao = GreenDaoManager.getInstance().getSession().getUserDao();
//当有多个相同名字的,一同修改
List<User> findUser = userDao.queryBuilder().where(UserDao.Properties.Name.eq(preName)).build().list();
if (findUser != null) {
for (int i = 0; i < findUser.size(); i++) {
findUser.get(i).setName(newName);
userDao.update(findUser.get(i));//更新名字
Toast.makeText(MainActivity.this, "update successful!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "no user!", Toast.LENGTH_SHORT).show();
}
}
完整代码:
package com.example.greendaotest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.greendaodtext.greendao.GreenDaoManager;
import com.example.greendaodtext.greendao.UserDao;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edit_text;
private Button btn_add;
private Button btn_delete;
private Button btn_update;
private Button btn_query;
private ListView listvew;
private List<User> userList = new ArrayList<>();
private ArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initView() {
edit_text = (EditText) findViewById(R.id.edit_text);
btn_add = (Button) findViewById(R.id.btn_add);
btn_delete = (Button) findViewById(R.id.btn_delete);
btn_update = (Button) findViewById(R.id.btn_update);
btn_query = (Button) findViewById(R.id.btn_query);
listvew = (ListView) findViewById(R.id.listview);
btn_add.setOnClickListener(this);
btn_delete.setOnClickListener(this);
btn_update.setOnClickListener(this);
btn_query.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
insert(null, edit_text.getText().toString());
break;
case R.id.btn_delete:
delete(edit_text.getText().toString());
break;
case R.id.btn_update:
update(edit_text.getText().toString(),"newName");
break;
case R.id.btn_query:
query();
break;
default:
break;
}
}
private void initData() {
//初始化数据,将数据库的查询结果显示在listview中
userList = GreenDaoManager.getInstance().getSession().getUserDao().queryBuilder().build().list();
adapter = new ArrayAdapter<User>(this, android.R.layout.simple_list_item_1, userList);
listvew.setAdapter(adapter);
}
//插入
public void insert(Long id, String name) {
User user = new User(id, name);
UserDao userDao = GreenDaoManager.getInstance().getSession().getUserDao();
userDao.insert(user);
}
//查询
public void query() {
UserDao userDao = GreenDaoManager.getInstance().getSession().getUserDao();
userList.clear();
userList.addAll(userDao.loadAll());//全部更新
adapter.notifyDataSetChanged();
}
public void delete(String name) {
UserDao userDao = GreenDaoManager.getInstance().getSession().getUserDao();
//当有多个相同名字的,一同删除
List<User> findUser = userDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().list();
if (findUser != null) {
for (int i = 0; i < findUser.size(); i++) {
//通过主键删除
userDao.deleteByKey(findUser.get(i).getId());
}
}
}
public void update(String preName, String newName) {
UserDao userDao = GreenDaoManager.getInstance().getSession().getUserDao();
//当有多个相同名字的,一同修改
List<User> findUser = userDao.queryBuilder().where(UserDao.Properties.Name.eq(preName)).build().list();
if (findUser != null) {
for (int i = 0; i < findUser.size(); i++) {
findUser.get(i).setName(newName);
userDao.update(findUser.get(i));//更新名字
Toast.makeText(MainActivity.this, "update successful!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "no user!", Toast.LENGTH_SHORT).show();
}
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.greendaotest.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_text"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add"
android:id="@+id/btn_add"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="del"
android:id="@+id/btn_delete"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="upd"
android:id="@+id/btn_update"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="que"
android:id="@+id/btn_query"
/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listview"
>
</ListView>
</LinearLayout>