GreenDao的简单使用
发布日期:2022-02-26 14:49:31 浏览次数:37 分类:技术文章

本文共 2297 字,大约阅读时间需要 7 分钟。

首先导入依赖 

将GreenDAO添加到项目中

GreenDAO可在Maven Central上使用。请确保您使用的是最新版本 

将以下Gradle配置添加到Android项目中:

// In your root build.gradle file:buildscript {    repositories {        jcenter()        mavenCentral() // add repository    }    dependencies {        classpath 'com.android.tools.build:gradle:3.1.1'        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin    }} // In your app projects build.gradle file:apply plugin: 'com.android.application'apply plugin: 'org.greenrobot.greendao' // apply plugin dependencies {    implementation 'org.greenrobot:greendao:3.2.2' // add library}

greendao {

schemaVersion 1 //版本

daoPackage '生成文件包名' // 一般为app包名+生成文件的文件夹名

targetGenDir 'src/main/java.greendao' //生成文件路径

}

 

创建实体类,生成dao文件

@Entitypublic class User {    @Id(autoincrement = true)    private Long id; //这里必须实用Long封装类型    private String userName;}

之后一下或者Ctrl+F9(Make project),程序会自动编译生成dao文件,生成的文件一共有三个。

在src/main/java.greendao  上面设置的路径里  greendao包中..

 

 

之后自己创建工具类

public class SqliteUtils {    private SQLiteDatabase db;    private DaoMaster mDaoMaster;    private DaoSession mSession;    private SqliteUtils() {    }    private static SqliteUtils mSqliteUtils;    public static SqliteUtils getSqliteUtils() {        if (mSqliteUtils == null) {            mSqliteUtils = new SqliteUtils();        }        return mSqliteUtils;    }    //初始化    public void init(Context context) {        //这里是数据库的名字"ming1"        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "ming1");        db = helper.getWritableDatabase();        mDaoMaster = new DaoMaster(db);        mSession = mDaoMaster.newSession();    }    //增    public void insert(User user){        mSession.getUserDao().insert(user);    }    //查询全部    public List
queryAll(){ return mSession.getUserDao().loadAll(); } //查询一条 public User query(Long key){ return mSession.getUserDao().load(key); } //删除全部 public void deleteAll(){ mSession.getUserDao().deleteAll(); } //删除单个 public void delete(String key){ mSession.getUserDao().deleteByKey(Long.parseLong(key)); } //更新 public void update(User user){ mSession.getUserDao().update(user); }}

 

 

之在项目中创建app包里面创建App类继承Application在

重写onCreate方法调用里面的init(Context context); 方法传入this   

记得在

里面声明~~~

之后就可以使用了大概~

 

转载地址:https://blog.csdn.net/qq_31353347/article/details/84346837 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android网络判断
下一篇:Retrofit+RxJava 的结合使用

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年03月19日 11时13分42秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章