Android GreenDao 3.0使用实例讲解

GreenDao简介

greenDAO是一个对象关系映射(ORM)的框架,能够提供一个接口通过操作对象的方式去操作关系型数据库,它能够让你操作数据库时更简单、更方便。

如何使用GreenDao 3.0

(1).新建Android项目工程,在工程目录的build.gradle中添加
dependencies { classpath ‘org.greenrobot:greendao-gradle-plugin:3.1.0’}
(2).在module的build.gradle文件中添加依赖
apply plugin: ‘org.greenrobot.greendao’
dependencies {compile ‘org.greenrobot:greendao:3.2.0’}
在android{}中添加
greendao
{
schemaVersion 1
targetGenDir ‘src/main/java/’
}
其中schmaVersion 表示数据库的版本,targetGenDir 表示编译后DaoMaster 、DaoSession、Dao文件的生成目录。

创建一个实体类:

@Entity
public class Cars
{
   //注意:通过@Property()这个注解定义我外部数据库的字段名才能解决
   //否则在插入数据的时候会报相关的错误。
    @Property(nameInDb = "id")
    @Id(autoincrement = true)
    private long id;
    @Property
    private String car_name;
    @Property
    private String car_price;
    @Property
    private String car_factory;
}

编译后自动生成三个类文件,如图所示:

创建一个数据库管理类,用于数据的插入,更新,删除,查询。代码如下:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;


/**
 1. 数据库管理类
 2. Created by admin on 2017/6/24.
 */
public class DBManager
{
    private static final String DB_NAME = "dao_db";
    private static DBManager instance;
    private DaoMaster.DevOpenHelper openHelper;

    private Context mContext;

    public DBManager(Context context)
    {
        this.mContext = context;
        openHelper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
    }

    public static DBManager getInstance(Context context)
    {
        if (instance == null)
        {
            synchronized (DBManager.class)
            {
                if (instance == null)
                {
                    instance = new DBManager(context);
                }
            }
        }
        return instance;
    }

    /**
     * 插入一条数据
     * @param car
     */
    public void insertUser(Cars car)
    {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CarsDao carsDao = daoSession.getCarsDao();
        carsDao.insert(car);
    }

    /**
     * 插入用户集合
     *
     * @param cars
     */
    public void insertUserList(List cars)
    {
        if (cars == null || cars.isEmpty())
        {
            return;
        }
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CarsDao carsDao = daoSession.getCarsDao();
        carsDao.insertInTx(cars);
    }

    public void update()
    {
        List carList = query();
        for (Cars car : carList)
        {
            if (car.getId() == 3)
            {
                car.setCar_price(88888888 +"");
                updates(car);
            }
        }
    }

    public void updates(Cars cars)
    {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CarsDao carsDao = daoSession.getCarsDao();
        carsDao.update(cars);
    }

    public void delete()
    {
        List userList = query();
        for (Cars car : userList)
        {
            if (car.getId() == 4)
            {
                delete(car);
            }
        }
    }


    public void delete(Cars cars)
    {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CarsDao carsDao = daoSession.getCarsDao();
        carsDao.delete(cars);
    }

    public List query()
    {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        CarsDao carsDao = daoSession.getCarsDao();
        QueryBuilder qb = carsDao.queryBuilder();
        List list = qb.list();
        return list;
    }

    /**
     * 获取可读数据库
     */
    public SQLiteDatabase getReadableDatabase()
    {
        if (openHelper == null)
        {
            openHelper = new DaoMaster.DevOpenHelper(mContext, "dao_db", null);
        }
        SQLiteDatabase db = openHelper.getReadableDatabase();
        return db;
    }

    /**
     * 获取可写数据库
     */
    public SQLiteDatabase getWritableDatabase()
    {
        if (openHelper == null)
        {
            openHelper = new DaoMaster.DevOpenHelper(mContext, "dao_db", null);
        }
        SQLiteDatabase db = openHelper.getWritableDatabase();
        return db;
    }
}

*相关的测试类:*

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity
{
    private ListView listView;
    DBManager dbManager;
    private List cars = new ArrayList<>();
    private MyAdapter myAdapter;
    private com.qihancloud.greendaotest.DaoMaster.DevOpenHelper openHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list);
        dbManager = new DBManager(MainActivity.this);
    }

    public void insert(View view)
    {
        cars.clear();
        for (int i = 0; i < 10; i++)
        {
            Cars user = new Cars();
            user.setId(i);
            user.setCar_name("飞车:" + i);
            user.setCar_price("100000" + i);
            user.setCar_factory("第" + i + "厂");
            cars.add(user);
        }

        DBManager.getInstance(MainActivity.this).insertUserList(cars);
    }

    public void update(View view)
    {
        DBManager.getInstance(MainActivity.this).update();
    }


    public void delete(View view)
    {
        DBManager.getInstance(MainActivity.this).delete();
    }

    public void query(View view)
    {
        cars = DBManager.getInstance(MainActivity.this).query();
        myAdapter = new MyAdapter(MainActivity.this, cars);
        listView.setAdapter(myAdapter);
    }
}

相关的布局文件就不贴代码了,喜欢的朋友欢迎交流学习。

你可能感兴趣的:(android,greendao)