greenDAO 官方替换数据库框架ObjectBox 学习 写记录1

greenDAO: Android ORM for your SQLite database

Note: for new apps we recommend ObjectBox, a new object-oriented database that is much faster than SQLite and easier to use. For existing apps based on greenDAO we offer DaoCompat for an easy switch (see also the announcement).

1.上代码(项目跟目录脚本)

 // Top-level build file where you can add configuration options common to all sub-projects/modules.
apply plugin: 'java'

apply plugin: 'io.objectbox'


buildscript {
//    ext.objectboxVersion = '1.2.1'
    repositories {
        jcenter()
        maven { url "http://objectbox.net/beta-repo/" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
        classpath "io.objectbox:objectbox-gradle-plugin:1.2.1"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "http://objectbox.net/beta-repo/" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
2.APP 目录的

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.org.gsc.opengldemo"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    // all below should be added automatically by the plugin

    compile "io.objectbox:objectbox-android:1.2.1"
    // some useful Kotlin extension functions
    // compile "io.objectbox:objectbox-kotlin:$objectboxVersion"

    annotationProcessor "io.objectbox:objectbox-processor:1.2.1"
    // When using Kotlin use kapt instead:
    // kapt "io.objectbox:objectbox-processor:$objectboxVersion"
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    testCompile 'junit:junit:4.12'
}
3. 初始化盒子

package com.org.gsc.opengldemo;

import android.app.Application;

import io.objectbox.BoxStore;

/**
 * Created by qundui on 2017/11/20.
 */

public class MyAPP extends Application {
    private BoxStore boxStore;

    public BoxStore getBoxStore() {
        return boxStore;
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        boxStore = MyObjectBox.builder().androidContext(App.this).build();
       boxStore = MyObjectBox.builder().androidContext(MyAPP.this).build();//初始化ORM 盒子
 do this in your activities/fragments to get hold of a Box
//        notesBox = ((MyAPP) geta).getBoxStore().boxFor(Student.class);

    }
}
4.act 中数据库操作
package com.org.gsc.opengldemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.util.List;

import io.objectbox.Box;
import io.objectbox.query.Query;

public class MainActivity extends AppCompatActivity {
    private Box<Student> notesBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        notesBox = ((MyAPP) getApplication()).getBoxStore().boxFor(Student.class);//获取Bean 模型
    }
    public void addData(View view){
        Student student=new Student();
//        student.id=0;
        student.name="fdy";
         notesBox.put(student);//添加
        Log.d("gsc",""+student.getId());
//        Student student1 = notesBox.get(8);
//        System.out.println("----读取--"+student1.getName());//查询
//        student1.setName("gsc");//修改
//        System.out.println("----读取修改后的--"+student1.getName());
        //删除
//        notesBox.remove(student1);//删除
        Query query = notesBox.query()
                .equal(Student_.name,"fdy").build();

        List<Student> persons = query.find();
        for(int i=0;i<persons.size();i++){
            Log.d("gsc",""+persons.get(i).getId());

        }
    }
}
4 项目Bean 表参考
package com.org.gsc.opengldemo;

import io.objectbox.annotation.Entity;
import io.objectbox.annotation.Id;

/**
 * Created by qundui on 2017/11/20.
 */
@Entity
public class Student {
        @Id
        long id;

        String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

 
 

GreenDao是一个高效、轻量级、快速的ORM(对象关系映射)框架,可以方便地将Java对象映射到SQLite数据库中。下面是GreenDao的引入和使用步骤: 1. 在build.gradle文件中添加以下依赖: ```groovy dependencies { implementation 'org.greenrobot:greendao:3.3.0' } ``` 2. 在app/build.gradle文件中添加以下配置: ```groovy android { defaultConfig { //... javaCompileOptions { annotationProcessorOptions { arguments = ["schemaVersion": "1", "daoPackage": "com.example.myapp.db"] } } } } greendao { schemaVersion 1 daoPackage 'com.example.myapp.db' targetGenDir 'src/main/java' } ``` 这些配置将告诉GreenDao在编译时生成DAO(数据访问对象)类。schemaVersion是数据库的版本号,daoPackage是生成DAO类的包名,targetGenDir是DAO类的生成目录。 3. 创建实体类,例如: ```java @Entity public class User { @Id(autoincrement = true) private Long id; private String name; private int age; // getters and setters } ``` @Entity注解表示这是一个实体类,@Id注解表示这是主键,autoincrement = true表示主键自增。 4. 在app/src/main/java目录下创建一个名为“greenDao”的包,并在该包下创建一个名为“DaoMasterOpenHelper”的类。该类继承自DaoMaster.OpenHelper,用于创建和升级数据库。例如: ```java public class DaoMasterOpenHelper extends DaoMaster.OpenHelper { public DaoMasterOpenHelper(Context context, String name) { super(context, name); } @Override public void onCreate(Database db) { super.onCreate(db); } @Override public void onUpgrade(Database db, int oldVersion, int newVersion) { // 数据库升级逻辑 } } ``` 5. 初始化GreenDao,在Application类的onCreate()方法中添加以下代码: ```java public class MyApp extends Application { private DaoSession daoSession; @Override public void onCreate() { super.onCreate(); DaoMasterOpenHelper helper = new DaoMasterOpenHelper(this, "mydb"); Database db = helper.getWritableDb(); daoSession = new DaoMaster(db).newSession(); } public DaoSession getDaoSession() { return daoSession; } } ``` 这里创建了一个DaoMasterOpenHelper实例,并通过它获取可数据库,然后创建一个DaoSession实例。 6. 使用GreenDao,例如: ```java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DaoSession daoSession = ((MyApp) getApplication()).getDaoSession(); User user = new User(); user.setName("Tom"); user.setAge(18); daoSession.getUserDao().insert(user); List<User> userList = daoSession.getUserDao().queryBuilder() .where(UserDao.Properties.Age.gt(10)) .orderAsc(UserDao.Properties.Age) .list(); } } ``` 这里通过getApplication()方法获取MyApp实例,然后通过getDaoSession()方法获取DaoSession实例。接着创建了一个User实例并插入到数据库中。最后使用查询构建器查询年龄大于10的所有用户,并按年龄升序排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江南一舟110

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值