GreenDao是一个关系型数据库,可方便的利用对象操作数据库,更可以利用其ORM的继承特性,整合代码编写。个人感觉就是给对于sql不熟练的我提供一个可以操作数据库的捷径。
GreenDao 官方地址:http://greenrobot.org/greendao/
GreenDao gitHub地址:https://github.com/greenrobot/greenDAO
本篇例程:http://download.csdn.NET/detail/xiaoleiacm/9538119
GreenDao的工程建立:
1 AS:在APP的Gradle中加入:(需要在GitHub上查找最新的版本)
- compile 'org.greenrobot:greendao:2.2.0'
2 建立一个java-gen
在APP的Gradle中的Android下加入:
- sourceSets{
- main{
- java.srcDirs=['src/main/java','src/main.java-gen']
- }
- }
3 新建一个java Library
命名为:
Library Name:greendaogenerator
Class Name:ExampleDaoGenerator (用于生成表对象)
生成如图结构
4 在greendaogenerator的Gradle中添加
- compile 'org.greenrobot:greendao-generator:2.2.0'
通过以上的设置已完成基本的Gradle设置。
ExampleDaoGenerator类是为了生成数据库表而建立的一个节点类,它需要完成数据库版本的建立,节点的建立,以及设置GreenDao核心代码的路径。
- package com.example;
- import de.greenrobot.daogenerator.DaoGenerator;
- import de.greenrobot.daogenerator.Entity;
- import de.greenrobot.daogenerator.Schema;
- public class ExampleDaoGenerator {
- public static void main(String[] args) {
- //生成实体类entity 即对应的表
- Schema schema = new Schema(1, "com.student.entity");
- //添加节点
- addStudent(schema);
- schema.setDefaultJavaPackageDao("com.student.dao");// 设置数据的会话层
- //将生成的内容放在指定的路径下C:\Users\admin\Desktop\shujuku\MyApplication\app\src\main\java-gen
- try {
- new DaoGenerator().generateAll(schema, "/Users/admin/Desktop/shujuku/MyApplication/app/src/main/java-gen");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- 创建数据库的表
- private static void addStudent(Schema schema) {
- Entity entity = schema.addEntity("Student"); //创建数据库的表
- /**
- * 设置字符串获其他类型为主键
- * entity.addStringProperty("身份证号").primaryKey();
- */
- //当前表中的列
- entity.addIdProperty();// 主键
- entity.addStringProperty("name");
- entity.addStringProperty("address");
- entity.addIntProperty("age");
- }
- }
生成GreenDao的CoreCode
运行ExampleDaoGenerator类,可以在Java-gen目录下生成相应的Student表的核心代码。
DaoMaster: 维护GreenDao数据库的对象,管理Dao生成的类
DaoSession:GreenDao的会话层,提供数据库的增删改查功能。
xxDao(StudentDao):比DaoSession更加具体的会话层,提供批量插入,Count等功能
Student:Student表的对象,里面包含着Student的表操作。
通过以上四个文件即可完成对关系对象型数据库GreenDao的操作。
GreenDao数据库的再封装:
由于数据库需要创建等有着大量的重复代码,可对GreenDao再封装。封装可分为数据库初始化,以及数据库调用接口。
数据库初始化:
由于数据库的操作,可使用的是单例模式,这样在创建DaoMaster时可使用synchronized防止出现多个数据库对象,保证了数据库的安全性。
对于数据库的初始化,可直接应用在其他工程中:
- package com.example.admin.myapplication.dbManager;
- import android.content.Context;
- import com.example.admin.myapplication.Dao.DaoMaster;
- import com.example.admin.myapplication.Dao.DaoSession;
- import de.greenrobot.dao.query.QueryBuilder;
- /**
- * 1 创建数据库
- * 2 创建数据库表
- * 3 创建数据库的增删查改
- * 4 对数据库的升级
- * Created by admin on 2016/5/31.
- */
- public class DaoManager {
- private static final String TAG = DaoManager.class.getSimpleName();
- private static final String DB_NAME = "mydb.sqlite"; //声明数据库
- private volatile static DaoManager manager; //多线程名称
- private static DaoMaster.DevOpenHelper helper;
- private static DaoMaster daomaster;
- private static DaoSession daoSession;
- private Context context;
- public void init(Context context) {
- this.context = context;
- }
- /**
- * 1 数据库类的创建
- * 线程安全创建DaoManager,使用单例模式获得操作数据库的对象
- *
- * @return note:为保证数据库的有效性,采用单利模式进行访问
- */
- public static DaoManager getInstance() {
- DaoManager instance = null;
- if (manager == null) {
- synchronized (DaoManager.class) {
- if (instance == null) {
- instance = new DaoManager();
- manager = instance;
- }
- }
- }
- return instance;
- }
- /**
- * 2 Master类的创建
- * 得到DaoMaster
- *
- * @return note:系统帮助用户监测是否有数据库,如果没有,则创建数据库
- */
- public DaoMaster getDaoMaster() {
- if (daomaster == null) {
- DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
- daomaster = new DaoMaster(helper.getWritableDatabase());
- }
- return daomaster;
- }
- /**
- * 3 数据库会话层DaoSession的创建
- * 完成对数据库的增删改查的操作,这里仅仅是一个接口。
- *
- * @return
- */
- public DaoSession getDaoSession() {
- if (daoSession == null) {
- if (daomaster == null) {
- daomaster = getDaoMaster();
- }
- daoSession = daomaster.newSession();
- }
- return daoSession;
- }
- /**
- * 关闭数据库的操作,使用完毕数据库,必须执行此操作。
- */
- public void CloseConnection() {
- CloseHelper();
- ColseDaoSession();
- }
- /**
- * 关闭helper
- */
- public void CloseHelper() {
- if (helper != null) {
- helper.close();
- helper = null;
- }
- }
- /**
- * 关闭Session会话层
- */
- public void ColseDaoSession() {
- if (daoSession != null) {
- daoSession.clear();
- daoSession = null;
- }
- }
- /**
- * 打开输出日志的操作
- */
- public void SetDebug() {
- QueryBuilder.LOG_SQL = true;
- QueryBuilder.LOG_VALUES = true;
- }
- }
调用接口实现:实现数据库的增删改查功能
- package com.example.admin.myapplication.dbManager;
- import android.content.Context;
- import android.database.Cursor;
- import android.util.Log;
- import com.example.admin.myapplication.Dao.Student;
- import com.example.admin.myapplication.Dao.StudentDao;
- import java.util.List;
- import de.greenrobot.dao.query.Query;
- import de.greenrobot.dao.query.QueryBuilder;
- import de.greenrobot.dao.query.WhereCondition;
- /**
- * Created by admin on 2016/5/31.
- */
- public class CommitUtils {
- private DaoManager manager;
- public CommitUtils(Context context) {
- manager = DaoManager.getInstance();
- manager.init(context);
- }
- /**
- * 完成对数据库表的插入操作
- *
- * @param student
- * @return
- */
- public boolean insertStudent(Student student) {
- boolean flag = false;
- flag = manager.getDaoSession().insert(student) != -1 ? true : false;
- return flag;
- }
- /**
- * 完成对数据库的多次插入
- *
- * @param students
- * @return
- */
- public boolean insertMultStudent(final List<Student> students) {
- boolean flag = false;
- try { // 启动一个线程,执行多次插入
- manager.getDaoSession().runInTx(new Runnable() {
- @Override
- public void run() {
- for (Student student : students) {
- manager.getDaoSession().insertOrReplace(student);
- }
- }
- });
- flag = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return flag;
- }
- /**
- * 更新对student某一条记录的修改
- * @param student
- * @return
- */
- public boolean updateStudent(Student student) {
- boolean flag = false;
- try {
- manager.getDaoSession().update(student);
- flag = true;
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- return flag;
- }
- /**
- * 删除一条数据
- * @param student
- * @return
- */
- public boolean deleteStudent(Student student) {
- boolean flag = false;
- try {
- // 删除一条记录
- manager.getDaoSession().delete(student);
- flag = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- // manager.getDaoSession().deleteAll(Student.class);
- return flag;
- }
- //
- /**
- * 返回多行记录
- * @return
- */
- public List<Student> ListAll() {
- return manager.getDaoSession().loadAll(Student.class);
- }
- /**
- * 按照主键返回单行记录
- * @param key
- * @return
- */
- public Student ListOneStudent(long key) {
- return manager.getDaoSession().load(Student.class, key);
- }
- /**
- * 查询数据 条件查询
- * @return
- */
- public List<Student> Query1() {
- return manager.getDaoSession().queryRaw(Student.class, "where name like ? and _id > ?", new String[]{"%张三%", "2"});
- }
- /**
- * 查询数据 对于数据库不熟悉可使用这种方式
- * @return
- */
- public List<Student> Query() {
- QueryBuilder<Student> builder = manager.getDaoSession().queryBuilder(Student.class);
- List<Student> list = builder.where(StudentDao.Properties.Age.between(23, 26))
- .where(StudentDao.Properties.Address.like("北京")).list();
- // builder.orderAsc(StudentDao.Properties.Age);
- return list;
- }
- }
通过上面的两层封装,可以方便的调用GreenDao.
调用代码:
- package com.example.admin.myapplication;
- import android.os.Bundle;
- import android.support.v7.app.AppCompatActivity;
- import android.util.Log;
- import android.view.View;
- import com.example.admin.myapplication.Dao.Student;
- import com.example.admin.myapplication.dbManager.CommitUtils;
- import java.util.ArrayList;
- import java.util.List;
- public class MainActivity extends AppCompatActivity {
- private static final String TAG="MainActivity";
- private CommitUtils commitUtils;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- commitUtils = new CommitUtils(this);
- }
- //插入数据
- public void InsertData(View view) {
- Log.i(TAG, "insert Data");
- Student student = new Student();
- student.setAddress("北京");
- student.setAge(23);
- student.setId(10001l);
- student.setName("张三");
- commitUtils.insertStudent(student);
- }
- //插入多条数据
- public void InsertMulData(View view) {
- Log.i(TAG, "insert Mut Data");
- List<Student> list = new ArrayList<>();
- for (int i = 0; i < 10; i++) {
- Student student = new Student();
- student.setAddress("北京");
- student.setAge(23 + i);
- // student.setId(10001l + i);
- student.setName("张三");
- list.add(student);
- }
- commitUtils.insertMultStudent(list);
- }
- /**
- * //更改数据
- * @param view
- */
- public void updataData(View view) {
- Log.i(TAG, "data Data");
- Student student = new Student();
- student.setAge(1000);
- student.setName("xiaolei");
- student.setId(1l);
- student.setAddress("2432");
- commitUtils.updateStudent(student);
- }
- public void deleteData(View view) {
- Student student = new Student();
- student.setId(2l);
- commitUtils.deleteStudent(student);
- }
- public void oneList(View view) {
- // Student student = commitUtils.ListOneStudent(1);
- Student student = commitUtils.ListOneStudent(1);
- Log.i(TAG, student.getName() + "");
- }
- public void mutiList(View view) {
- List<Student> list = commitUtils.ListAll();
- // if(list!=null)
- Log.i(TAG, list.toString());
- }
- public void QueryData(View view){
- // List<Student> query = commitUtils.Query();
- // for(int i=0;i<query.size();i++)
- // {
- // Log.i(TAG, query.get(i).getAge().toString()+" :"+ query.get(i).getId()) ;
- // }
- List<Student> students = commitUtils.Query();
- if(students!=null)
- for(int i=0;i<students.size();i++) {
- Log.i(TAG, students.get(i).getAge() + " :" + students.get(i).getId());
- }
- }
- }