欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

GreenDao数据库

程序员文章站 2024-03-21 10:04:46
...

ORM框架

首先,来认识ORM是什么

ORM是一种对象关系映射,它的实现思想就是把数据库的表数据映射成对象,以便我们对这些对象的操作,我们把对数据库的操作简化成对对象的操作,提高开发效率。

GreenDao

这里参考了老罗视频第三季的视频,总结一下,做了个小实例

关于GreenDao的配置

  1. 建包

新建一个与java同级别的包以及一个Module(daogenerator),选择的是javaLibrary

GreenDao数据库

GreenDao数据库

2、 在module包中写一个类
在module里面也要导第三方包

public class DaoMaker {
    public static void main(String[] args){
        //生成数据库的实体类XXentity 对应的是数据库的表,参数1是版本号
        Schema schema = new Schema(1,"com.student.entity");
        //添加一张表
        addStudent(schema);
        schema.setDefaultJavaPackageDao("com.student.dao");
        try {
            //生成到java-gen,传入javagen的地址
            new DaoGenerator().generateAll(schema,"E:\\Frame\\app\\src\\main\\java-gen");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void addStudent(Schema schema){
        //创建数据库的表
        Entity entity = schema.addEntity("Student");
        //主键是int类型
        entity.addIdProperty();
        entity.addStringProperty("name");
        entity.addStringProperty("address");
        entity.addIntProperty("age");
    }
}

在原来的项目中的build.gradle中添加依赖

//greendao依赖
    compile 'de.greenrobot:greendao:2.1.0'
    compile 'de.greenrobot:greendao-generator:2.1.0'
android {
    sourceSets{
        main{
            java.srcDirs=['src/main/java','src/main/java-gen']
        }
     }
   }

运行之后javagen就有类了

GreenDao数据库

GreenDao的核心类

  • greendao-generator.jar产生的是DAO的接口(即我们建立的Mdoule包产生的接口)
  • 核心的greendao.jar产生的类

    GreenDao数据库

XXEntity:对应的是数据库的表。

DaoMester: 就是用来建表和删除表,并且提供了内部帮助类OpenHelper,DevOpenHelper

DaoSession: 对应的会话层,具体操作数据库表对应的对象,并且提供了对应的增删改查的操作

XXDao: 通常对应具体的java类,为每一个数据库表对象创建一个DAO,它有批量或者具体操作数据的方法,比DaoSession更牛逼

Schema : 生产实体对象的类

3、操作数据库

  • 建立一个管理数据库的类,对数据库对象进行获取,创建,删除,提供操作的接口
public class DBManager {
    public static final String TAG = DBManager.class.getSimpleName();
    public static final String DB_NAME = "mydb.sqlite";
    //多线程访问
    public volatile static DBManager dbManager;
    public static DaoMaster.DevOpenHelper devOpenHelper;
    public static DaoSession daoSession;
    public static DaoMaster daoMaster;
    public Context context;
    /**
     * 单例模式获取操作数据库对象
     * @return
     */
    public static DBManager getInstance(){
        DBManager instance = null;
        if(dbManager == null){
            synchronized (DBManager.class){
                if(instance == null){
                    dbManager = new DBManager();
                    instance = dbManager;
                }
            }
        }
        return instance;
    }
    public void init(Context context){
        this.context = context;
    }
    /**
     * 判断是否创建数据库,没有就创建
     * @return
     */
    public DaoMaster getDaoMaster(){
        if(daoMaster == null){
            DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(context,DB_NAME,null);
            daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        }
        return daoMaster;
    }
    /**
     * 完成对数据库的操作 ,仅仅是个接口
     * @return
     */
    public DaoSession getDaoSession(){
        if(daoSession == null){
            if(daoMaster == null){
                daoMaster = getDaoMaster();
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }
    /**
     * 打开输出日志的方法
     */
    public void setDug(){
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
    }
    /**
     * 关闭所有操作
     */
    public void closeConnection(){
        closeHelper();
        closeSession();
    }
    public void closeSession(){
        if(daoSession != null){
            daoSession.clear();
            daoSession = null;
        }
    }
    public void closeHelper(){
        if(devOpenHelper != null){
            devOpenHelper.close();
            devOpenHelper = null;
        }
    }
}
  • 封装一个工具类,实现操作接口,对数据进行操作
package com.gzucm.frame.GreenDao.dbManager;
import android.content.Context;
import com.student.dao.StudentDao;
import com.student.entity.Student;
import java.util.List;
import de.greenrobot.dao.query.QueryBuilder;

public class CommonUtils {
    private DBManager dbManager;
    public CommonUtils(Context context){
        dbManager = DBManager.getInstance();
        dbManager.init(context);
    }
    public boolean insertStudent(Student student){
        boolean flag = false;
        flag = dbManager.getDaoSession().insert(student) != -1? true:false;
        return flag;
    }
    public boolean insertMultStudent(final List<Student> students){
        boolean flag = false;
        try{
            dbManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for(Student student:students){
                        dbManager.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{
            dbManager.getDaoSession().update(student);
            flag = true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return  flag;
    }
    /**
     * 删除一条记录
     * @param student
     * @return
     */
    public boolean deleteStudent(Student student){
        boolean flag = false;
        try{
            dbManager.getDaoSession().delete(student);
            flag = true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return  flag;
    }
    /**
     * 删除所有记录
     * @param cls
     * @return
     */
    public boolean deleteAllStudent(Class cls){
        boolean flag = false;
        try{
            //删除Student所有对象
            dbManager.getDaoSession().deleteAll(Student.class);
            flag = true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return  flag;
    }
    /**
     * 返回多条记录
     * @return
     */
    public List<Student> listAll(){
        return dbManager.getDaoSession().loadAll(Student.class);
    }
    /**
     * 按照主键返回单行记录
     * @param key
     * @return
     */
    public Student listOneStudent(long key){
        return dbManager.getDaoSession().load(Student.class,key);
    }
    public void query1(){
        //使用native sql进行查询操作
        List<Student> list = dbManager.getDaoSession().queryRaw(Student.class,
                " where name like ? and _id > ? ",new String[]{"%李%","1001"});
    }
    public void query2(){
        QueryBuilder<Student> builder = dbManager.getDaoSession().queryBuilder(Student.class);
        List<Student> list = builder.where(StudentDao.Properties.Age.ge(23))
                .where(StudentDao.Properties.Address.like("江西")).list();
    }
    public void query3(){
        QueryBuilder<Student> builder = dbManager.getDaoSession().queryBuilder(Student.class);
        builder.whereOr(StudentDao.Properties.Age.ge(50),StudentDao.Properties.Address.eq("北京"));
        //取前三条数据
        builder.whereOr(StudentDao.Properties.Id.ge(2),StudentDao.Properties.Age.ge(10)).limit(3);
        List<Student> list = builder.list();
    }
}
  • 对应的activity,通过UI进行操作数据
package com.gzucm.frame.GreenDao;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import com.gzucm.frame.GreenDao.dbManager.CommonUtils;
import com.gzucm.frame.R;
import com.student.entity.Student;
import java.util.ArrayList;
import java.util.List;

public class GreenActivity extends AppCompatActivity{
    private ListView lv_content;
    private StudentListAdapter adapter;
    private List<Student> students;
    CommonUtils commonUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activitygreendao);
        lv_content = (ListView) findViewById(R.id.lv_content);
        commonUtils = new CommonUtils(this);
        insertMultData();
    }
    public void add(View view){
        addStudent();
    }
    public void delete(View view){
        commonUtils.deleteAllStudent(Student.class);
//        insertMultData();
    }
    public void update(View view){
        updateStudent();
    }
    public void query(View view){
        queryStudent();
    }
    public void insert(View view){
        insertMultData();
    }
    private void queryStudent() {
//        students = new ArrayList<>();
        students = commonUtils.listAll();
        adapter = new StudentListAdapter(this, students);
        lv_content.setAdapter(adapter);
    }
    private void addStudent() {
        Student student = new Student();
        student.setAddress("广州三元里");
        student.setName("XXX");
        student.setAge(22);
        student.setId(5201314l);
        commonUtils.insertStudent(student);
        queryStudent();
    }
    private void updateStudent() {
        Student student = new Student();
        student.setId(1l);
        student.setAge(100);
        student.setName("jack");
        student.setAddress("北京育知同创科技有限公司");
        commonUtils.updateStudent(student);
        queryStudent();
    }
    public void insertMultData(){
        List<Student> students = new ArrayList<>();
        for(int i=0;i<10;i++){
            Student student = new Student();
            student.setAddress("江西");
            student.setName("李四" +i);
            student.setAge(24+i);
            students.add(student);
        }
        commonUtils.insertMultStudent(students);
        queryStudent();
    }
}
package com.gzucm.frame.GreenDao;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.gzucm.frame.R;
import com.student.entity.Student;
import java.util.List;

public class StudentListAdapter extends BaseAdapter {
    private List<Student> list;
    private LayoutInflater mInflater;
    public StudentListAdapter(Context context, List<Student> list) {
        this.list = list;
        mInflater = LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        return list.size();
    }
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.activity_greendao_item, null);
        }
        ViewHolder holder = getViewHolder(convertView);
        Student student = list.get(position);
        holder.tv_name.setText(student.getName());
        holder.tv_address.setText(student.getAddress());
        holder.tv_age.setText(student.getAge() + "");
        holder.tv_id.setText(student.getId() + "");
        return convertView;
    }
    /**
     * 获得控件管理对象
     *
     * @param view
     * @return
     */
    private ViewHolder getViewHolder(View view) {
        ViewHolder holder = (ViewHolder) view.getTag();
        if (holder == null) {
            holder = new ViewHolder(view);
            view.setTag(holder);
        }
        return holder;
    }
    /**
     * 控件管理类
     */
    private class ViewHolder {
        private TextView tv_name, tv_address, tv_age, tv_id;
        ViewHolder(View view) {
            tv_name = (TextView) view.findViewById(R.id.textView);
            tv_address = (TextView) view.findViewById(R.id.textView2);
            tv_age = (TextView) view.findViewById(R.id.textView3);
            tv_id = (TextView) view.findViewById(R.id.textView4);
        }
    }
}

GreenDao数据库

相关标签: 框架