GreenDao的简单使用

首先导入依赖 

将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文件

@Entity
public 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<User> 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   

记得在

里面声明~~~

之后就可以使用了大概~

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值