GreenDao在Android Studio中的使用

来源:互联网 发布:面试常用的排序算法 编辑:程序博客网 时间:2024/05/16 16:59

GreenDao3.0使用

  因为本人使用的开发工具是Android Studio,所以只讲解一下GreenDao在Android Studio中的使用。

1、GreenDao的介绍

  • GreenDao简介

  greenDAO是一个轻量、快速的ORM(对象关系映射)解决方案,它将对象映射到SQLite数据库,这样就可以通过简单的面向对象的接口来增加、删除、更新、查询Java对象,大大减少了工作任务。

  • GreenDao优点

  ①.性能最大化,号称Android最快的关系型数据库

  ②.内存占用极小

  ③.库文件比较小,只有不到100K

  ④.支持数据库加密

  ⑤.简洁易用的API

2、GreenDao的配置

  • 配置Project的build.gradle
 buildscript {    repositories {        jcenter()        //添加一个仓库        mavenCentral()     }    dependencies {        classpath 'com.android.tools.build:gradle:2.3.1'        //添加的内容        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'     }}
  • 配置Model的build.gradle
apply plugin: 'com.android.application'// 添加GreenDao的pluginapply plugin: 'org.greenrobot.greendao' //配置GreenDao文件生成位置,它的级别是与Android标签和dependencies标签一个级别的greendao {    //数据库的版本号,数据库版本升级的时候用得到    schemaVersion 2;    //生成的Daos、DaoMaster路径,我选择的是生成在自己的实体类文件下    daoPackage "com.rushro2m.greendao_master.bean"    //生成的资源路径,默认存放在build中    targetGenDir "src/main/java"}    dependencies {    // 添加GreenDao的library    compile 'org.greenrobot:greendao:3.2.2' }

  配置成功后,进行同步。

  • 在自己创建的bean包中创建一个实体类,我这里创建的是MovieBean实体类。

  参数说明:这个@Entity说明这个MovieBean是一个实体类,一会会在数据库中生成对应的表。@Id表示该字段的id,这里使用的是Long包装类型,这样的话,可以实现id的自增效果,当然也可以使用long类型,不过要设置上自增属性,@Property表名这个字段是要放入到数据库中去的,nameInDb表示此字段在数据库中的数据名称,也可以不设置,那么就会使用默认字段,即使用变量名。其它的还有就是@Transient,表示该字段不会放入数据库,@NotNull表示该字段不可以为空,@Unique表示该字段唯一等。

@Entitypublic class MovieBean {    @Id    private Long id;    @Property(nameInDb = "TITLE")    private String title;    @Property(nameInDb = "IMAGE")    private String image;}//也可以这样写@Entitypublic class MovieBean {    @Id(autoincrement = true)    private long id;    @Property    private String title;    @Property    private String image;}

  完成后,点击Build–>Make Project按钮,或者直接点击运行按钮旁边的绿色小锤子,等待系统自动生成GreenDao文件。系统会生成三个文件DaoMaster,DaoSession,MovieBeanDao三个文件,并在MovieBean中自动生成setter和getter方法。

3、GreenDao的使用

  • 数据库的初始化

  数据库的初始化我一般都放在自定义的Application的子类中,因为Application是一个全局变量,随着App的整体而变化,记得要在清单文件中进行注册。

public class MyApp extends Application {    private DaoSession daoSession;    @Override    public void onCreate() {        super.onCreate();        //实例化一个OpenHelper实例,类似于使用的SQLiteOpenHelper类        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "movie-db");        //获取一个SQLiteDatabase        SQLiteDatabase database = helper.getWritableDatabase();        //使用数据库对象构造一个DaoMaster        DaoMaster daoMaster = new DaoMaster(database);        //开启DoaSession        daoSession = daoMaster.newSession();    }    public DaoSession getDaoSession() {        return daoSession;    }}
  • 创建布局

  打开res–>layout–>activity_main.xml文件,添加如下控件:

<?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.rushro2m.greendao_master.MainActivity">    <Button        android:id="@+id/main_insert"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="onClick"        android:text="插入一个电影" />    <Button        android:id="@+id/main_query"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="onClick"        android:text="查询电影" />    <Button        android:id="@+id/main_delete"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="onClick"        android:text="删除一条电影" />    <Button        android:id="@+id/main_update"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="onClick"        android:text="更新一条电影" />    <android.support.v7.widget.RecyclerView        android:id="@+id/recycler_main"        android:layout_width="match_parent"        android:layout_height="match_parent" /></LinearLayout>

  新建一个子布局,里面只有一个TextView,用来显示文本内容

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical">        <TextView            android:id="@+id/tv_item"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:gravity="center"            android:text="tv_item"            android:textSize="20sp" /></LinearLayout>
  • 创建RecyclerView的适配器
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {    private List<MovieBean> mData;    private LayoutInflater inflater;    private Context mContext;    public MyAdapter(List<MovieBean> mData, Context mContext) {        this.mData = mData;        this.mContext = mContext;        inflater = LayoutInflater.from(mContext);    }    @Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        View itemView = inflater.inflate(R.layout.item, parent, false);        return new ViewHolder(itemView);    }    @Override    public void onBindViewHolder(ViewHolder holder, int position) {        holder.tv.setText("ID:" + mData.get(position).getId() + "--->TITLE:" + mData.get(position).getTitle());    }    @Override    public int getItemCount() {        return mData.size();    }    class ViewHolder extends RecyclerView.ViewHolder {        TextView tv;        ViewHolder(View itemView) {            super(itemView);            tv = (TextView) itemView.findViewById(R.id.tv_item);        }    }}

  首先创建一个方法,每次增删改查完之后,将数据库重新查询一遍,并将数据通过RecyclerView展示出来;

private void queryMovieBean() {    DaoSession daoSession = ((MyApp) getApplication()).getDaoSession();    MovieBeanDao movieBeanDao = daoSession.getMovieBeanDao();    Query<MovieBean> query = movieBeanDao.queryBuilder().build();    MyAdapter myAdapter = new MyAdapter(query.list(), this);    recycler.setAdapter(myAdapter);}
  • 实现增的功能

  通过点击增加按钮,向数据库增加一条数据,增加后,显示新的列表。

private void insertMovie() {        MovieBean movie = new MovieBean();        movie.setTitle("这是第" + ++i + "条数据。");        DaoSession daoSession = ((MyApp) getApplication()).getDaoSession();        MovieBeanDao movieBeanDao = daoSession.getMovieBeanDao();        movieBeanDao.insert(movie);        queryMovieBean();}
  • 实现删的功能

  通过点击删除按钮,删除数据库中的某一条数据,删除后,显示新的列表。

private void deleteMovie() {    DaoSession daoSession = ((MyApp) getApplication()).getDaoSession();    MovieBeanDao movieBeanDao = daoSession.getMovieBeanDao();    Query<MovieBean> query = movieBeanDao.queryBuilder()                        .where(MovieBeanDao.Properties.Id.eq(10))                        .build();    MovieBean movieBean = query.unique();    if (movieBean != null) {        movieBeanDao.delete(movieBean);        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();    } else {        Toast.makeText(this, "此条数据不存在", Toast.LENGTH_SHORT).show();    }    queryMovieBean();}
  • 实现改的功能

  通过点击更新按钮,更改数据库中的某一条数据,更改成功后,显示新的列表。

private void updateMovie() {    //先查询数据,在修改数据,然后更新到数据库中去    DaoSession daoSession = ((MyApp) getApplication()).getDaoSession();    MovieBeanDao movieBeanDao = daoSession.getMovieBeanDao();    Query<MovieBean> movieBeanQuery = movieBeanDao.queryBuilder()                        .where(MovieBeanDao.Properties.Id.eq(5))                        .build();    List<MovieBean> beanList = movieBeanQuery.list();    if (beanList != null) {        for (MovieBean movie : beanList) {            movie.setTitle("这条是更新的数据。");            movieBeanDao.update(movie);        }        Toast.makeText(this, "数据更新完成", Toast.LENGTH_SHORT).show();    } else {        Toast.makeText(this, "数据不存在", Toast.LENGTH_SHORT).show();    }    queryMovieBean();}
  • 实现查的功能

  通过点击查询按钮,查询数据库中是否存在某一条数据。

private void queryMovie() {    //查询某条数据是否存在    DaoSession daoSession = ((MyApp) getApplication()).getDaoSession();    MovieBeanDao movieBeanDao = daoSession.getMovieBeanDao();    Query<MovieBean> beanQuery = movieBeanDao.queryBuilder()                        .where(MovieBeanDao.Properties.Id.eq(15))                        .build();    MovieBean movieBean = beanQuery.unique();    if (movieBean != null) {        Toast.makeText(this, "数据查询成功", Toast.LENGTH_SHORT).show();    } else {        Toast.makeText(this, "这条数据不存在", Toast.LENGTH_SHORT).show();    }    queryMovieBean();}

  无论是删还是改之前,都要先对数据中的数据进行查询,确定这条数据存在,才能对其进行删改操作。

  项目源码地址

原创粉丝点击