2019-01-14数据库配置流程

1.要在project对应项目的build.gradle里面配置依赖包

要在project对应项目的build.gradle 里面配置依赖包

buildscript {

    repositories {

        jcenter()

    }

    dependencies {

        classpath 'com.android.tools.build:gradle:2.1.0'

        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'

    }

}

第二步

要在新建的module模块对应的build.gradle里面配置依赖包以及生成类的位置

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])        testCompile 'junit:junit:4.12'

      compile 'com.android.support:appcompat-v7:23.4.0

          compile 'org.greenrobot:greendao:3.2.0'

}第三步 在顶部声明部位 apply plugin: 'org.greenrobot.greendao'第四步 在android{}添加  daoPackage 包名可以修改 greendao{

    schemaVersion 1

    daoPackage 'com.jiyun.com.day07_greendao'

          targetGenDir 'src/main/java'

5.配置好之后,点Sync now 就会自动下载greenDAO对应的jar包

配置好后就可以使用GreenDao进行增删改查 实体类:  MyBean  使用注册的形式@Entity(nameInDb = "jia")

public class MyBean {

    @Id(autoincrement = true)

    private long id;

    @Unique

    @NotNull

    @Property(nameInDb = "name")

    private String name;

    @Property(nameInDb = "content")

    private String content;

    @Property(nameInDb = "img")

    private int img ;

    @Generated(hash = 293826196)

    public MyBean(long id, @NotNull String name, String content, int img) {

        this.id = id;

        this.name = name;

        this.content = content;

        this.img = img;

    }

    @Generated(hash = 1281580447)

    public MyBean() {

    }

    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;

    }

    public String getContent() {

        return content;

    }

    public void setContent(String content) {

        this.content = content;

    }

    public int getImg() {

        return img;

    }

    public void setImg(int img) {

        this.img = img;

    }

}

写完实体类之后重新编译,生成三个类 DaoMesster UserDao DaoSession 然后我们可以使用单例模式创建数据库, DaoManger public class DaoManager { private static DaoManager manager; private DaoMaster.DevOpenHelper helper;    public static final String DB_NAME = "student1.db";  private DaoManager(Context context){        helper = new DaoMaster.DevOpenHelper(context,DB_NAME);    }    public static synchronized DaoManager getInstance(Context context){        if(manager==null)            manager = new DaoManager(context);        return manager;    }    public StudentDao getDao(){        DaoMaster master = new DaoMaster(helper.getWritableDatabase());        DaoSession daoSession = master.newSession();        StudentDao studentDao = daoSession.getStudentDao();        return studentDao;    }}

你可能感兴趣的:(2019-01-14数据库配置流程)