Android 关于数据库GreenDao导入到AndroidStudio中

1.在项目根目录 build.gradle 添加如下代码并执行同步操作

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'

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

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

2.在app目录 build.gradle 添加apply plugin: ‘org.greenrobot.greendao’,并添加依赖
implementation ‘org.greenrobot:greendao:3.2.2’,同步一下,如下

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
implementation 'org.greenrobot:greendao:3.2.2'

3.在app目录 build.gradle android下添加

greendao {
    //数据库的schema版本,也可以理解为数据库版本号
    schemaVersion 1
    //设置DaoMaster、DaoSession、Dao包名,也就是要放置这些类的包的全路径。
    daoPackage '你的包名.dao'
    //设置DaoMaster、DaoSession、Dao目录
    targetGenDir 'src/main/java'
}

4.新建一个实体类User,如下

@Entity
public class User {
    @Id(autoincrement = true)
    private Long id; //特别说明,必须是Long
    private String name;
    private String age;
}

点击build–>>>Make Project,会看到User类中自动生成的代码,如下

@Entity
public class User {
    @Id(autoincrement = true)
    private Long id; //特别说明,必须是Long
    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;
    }
}

并在项目中自动生成了dao,如下

到此,完事啦

你可能感兴趣的:(Android 关于数据库GreenDao导入到AndroidStudio中)