android 框架 GreeDao 配置和使用详解

本文详细介绍了Android数据库ORM框架GreenDao,强调了其性能优势和对protobuf协议的支持。通过Code generation实现高性能,同时提供了配置GreenDao在Android Studio中的步骤,包括实体类注解、索引、关系映射的详细说明,并指导如何初始化数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 ,介绍篇

greenDAO是一种Android数据库ORM(object/relational mapping)框架,与OrmLite、ActiveOrm、LitePal等数据库相比,单位时间内可以插入、更新和查询更多的数据,而且提供了大量的灵活通用接口。

简单的讲,greenDAO 是一个将对象映射到 SQLite 数据库中的轻量且快速的 ORM 解决方案。(greenDAO is a light & fast ORM solution that maps objects to SQLite databases.) 

greenDAO 性能远远高于同类的 ORMLite,具体测试结果可见官网

greenDAO 支持 protocol buffer(protobuf) 协议数据的直接存储,如果你通过 protobuf 协议与服务器交互,将不需要任何的映射。与 ORMLite 等使用注解方式的 ORM 框架不同,

greenDAO 使用「Code generation」的方式,这也是其性能能大幅提升的原因。

二,android studio 配置GreeDao

build.gradle(Project:)

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'

        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}

build.gradle(Module:)

apply plugin: 'com.android.application'
//使用greendao
apply plugin: 'org.greenrobot.greendao'

android {
    compileSdkVersion 25
    buildToolsVersion "27.0.2"

    defaultConfig {
        applicationId "com.sun.mygreedaodemo"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
greendao {
    schemaVersion 1
    schemaVersion 1//数据库版本号
    daoPackage 'com.sun.greendao'//设置DaoMaster、DaoSession、Dao包名
    targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录


}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'org.greenrobot:greendao:3.2.0'
}

接着就是实体类

@Entity
public class Users {
    @Id(autoincrement = true)//主键自增
    private Long id;

    private  String  name;
    private  String age;
}
  • 实体@Entity注解

    schema:告知GreenDao当前实体属于哪个schema
    active:标记一个实体处于活跃状态,活动实体有更新、删除和刷新方法
    nameInDb:在数据库中使用的别名,默认使用的是实体的类名
    indexes:定义索引,可以跨越多个列
    createInDb:标记创建数据库表

  • 基础属性注解

    @Id:主键 Long 型,可以通过@Id(autoincrement = true)设置自增长
    @Property:设置一个非默认关系映射所对应的列名,默认是使用字段名,例如:@Property(nameInDb = "name")
    @NotNull:设置数据库表当前列不能为空
    @Transient:添加此标记后不会生成数据库表的列

  • 索引注解

    @Index:使用@Index作为一个属性来创建一个索引,通过name设置索引别名,也可以通过unique给索引添加约束
    @Unique:向数据库添加了一个唯一的约束

  • 关系注解

    @ToOne:定义与另一个实体(一个实体对象)的关系
    @ToMany:定义与多个实体对象的关系

当我们编写好实体类并添加自己需要的注解之后,点击Make Project或者Make Module 'app',就会项目的build目录下或者自己设定的目录下看到生成的三个类文件:

实体类

@Entity
public class User {
    //不能用int
    @Id(autoincrement = true)
    private Long id;

    private  String  name;
    private  String age;
    @Generated(hash = 1666193281)
    public User(Long id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    @Generated(hash = 586692638)
    public User() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return this.age;
    }
    public void setAge(String age) {
        this.age = age;
    }
}

三 初始化数据库(数据库自定义文件夹)

1.重新  ContextWrapper

public class GreenDaoContext  extends ContextWrapper{

    private String currentUserId;
    private Context mContext;

    public GreenDaoContext(Context base) {
        super(base);
    }


    @Override
    public File getDatabasePath(String name) {
        // 判断是否存在sd卡  
        boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
        if (!sdExist) {// 如果不存在,  
            Log.e("SD卡管理:", "SD卡不存在,请加载SD卡");
            return null;
        } else {// 如果存在  
            // 获取sd卡路径 
            Log.e("SD卡管理:", "SD卡存在,将在sd卡上创建数据库..");
            String dbDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
            dbDir += "/AAAAAA";// 数据库所在目录
            String dbPath = dbDir + "/" + name;// 数据库路径  
            // 判断目录是否存在,不存在则创建该目录  
            File dirFile = new File(dbDir);
            if (!dirFile.exists())  {
                dirFile.mkdirs();
                Log.e("SD卡管理:", "创建文件" + dbDir);
            } else {
                Log.e("SD卡管理:", dbDir + "文件存在");
            }
            // 数据库文件是否创建成功  
            boolean isFileCreateSuccess = false;
            // 判断文件是否存在,不存在则创建该文件  
            File dbFile = new File(dbPath);
            if (!dbFile.exists()) {
                try {
                    Log.e("SD卡管理:", dbPath + ":创建");
                    isFileCreateSuccess = dbFile.createNewFile();// 创建文件  
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else  {
                Log.e("SD卡管理:", dbPath + ":已存在");
                isFileCreateSuccess = true;
            }
            // 返回数据库文件对象  
            if (isFileCreateSuccess) {
                Log.e("SD卡管理:", "isFileCreateSuccess=" + isFileCreateSuccess);
                return dbFile;
            } else  {
                Log.e("SD卡管理:", "isFileCreateSuccess=" + isFileCreateSuccess);
                return super.getDatabasePath(name);
            }
        }

    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode,SQLiteDatabase.CursorFactory factory) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
        return result;
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory,DatabaseErrorHandler errorHandler) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);

        return result;
    }

}

2.初始化

public class MyApplication extends Application {

    private static DaoSession mydaoSession;
    public static MyApplication myApplication;
    public static DaoMaster myDaoMaster;

    public static SQLiteDatabase db;
    public DaoMaster.DevOpenHelper helper;

    public static MyApplication getInstance(){
        if (myApplication == null) {
            myApplication = new MyApplication();
        }
        return myApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setupDatabase();
    }

    private void setupDatabase() {
        helper = new DaoMaster.DevOpenHelper(new GreenDaoContext(myApplication),"mylike.db",null);
        //得到数据库连接对象
        db = helper.getWritableDatabase();
        //得到数据库管理者
        myDaoMaster= new DaoMaster(db);
        //得到daoSession,可以执行增删改查操作
        mydaoSession = myDaoMaster.newSession();
    }


    //得到数据库管理
    public  static  DaoMaster getDaoMaster(Context context){
        if(myDaoMaster ==null){
            DaoMaster.OpenHelper openHelper = new DaoMaster.DevOpenHelper(new GreenDaoContext(myApplication),"mylike.db",null);
            myDaoMaster= new DaoMaster(openHelper.getWritableDatabase());
        }
        return myDaoMaster ;
    }
   // //得到daoSession,可以执行增删改查操作
    public  static DaoSession getDaoSession(Context context){
        if(mydaoSession == null){
            if(myDaoMaster ==null){
               myDaoMaster = getDaoMaster(context);
            }
            mydaoSession = myDaoMaster.newSession();
        }
        return mydaoSession ;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

}

记得权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE"/>

运行 数据库就建好了。

四 Bbhepler类

   //插入数据
    public  static  void  insertdata(Context context, User user){
        MyApplication.getDaoSession(context).getUserDao().insert(user);
    }
    //查找数据
    public  static  List<User> queryAll(Context context){
        QueryBuilder<User> builder = MyApplication.getDaoSession(context).getUserDao().queryBuilder();
        return  builder.build().list();
    }
    //分列查询
    public  static  List<User> querypage(Context context,int pageSize,int pageNum){
        UserDao userdao= MyApplication.getDaoSession(context).getUserDao();
        List<User> list=userdao.queryBuilder().offset(pageSize * pageNum).limit(pageNum).list();
        return  list;
    }
    //条件查询
    public  static  List<User> qureyuser(Context context,String name){
        UserDao userdao= MyApplication.getDaoSession(context).getUserDao();
        List<User> list= userdao.queryBuilder().where(UserDao.Properties.Name.eq(name)).list();
      return list;
    }
    //根据删除表数据
    public  static void deletuser(Context context){
        UserDao userdao= MyApplication.getDaoSession(context).getUserDao();
        userdao.deleteAll();
    }
    //删除Visitor表
    public void dropAccountTable(Context context){
        UserDao.dropTable(MyApplication.getDaoSession(context).getDatabase(), true);
    }
下载源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值