本文内容:
本文的内容主要是针对使用Kotlin开发android过程中使用Greendao3来操作数据库的基本使用指南。由于Greendao3相关资料比较多,请大家自行搜索,本文不再对Greendao3进行详细介绍。
Greendao3配置:
在使用Greendao3之前,需要对Greendao3进行配置(这已经是默认流程了!),打开build.gradle(Module:app)添加如下配置:
apply plugin: 'org.greenrobot.greendao'
compile 'org.greenrobot:greendao:3.2.2'
下面字段中schemaVersion配置数据库的版本,daoPackage是配置在工程中Greendao的包名,targetGenDir是配置数据库的保存路径。
greendao {
schemaVersion 1
daoPackage 'GreenDao'
targetGenDir 'src/main/java'
}
在Build.gradle(project:xxx)中添加如下配置:
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
配置完成后编译工程,可以看到在工程中出现GreenDao包。如下图所示。
Greendao3使用:
完成配置后便可以进行使用,在使用时要进行实体类的编写,创建实体类User:
Greendao3中,实体类需要用@Entity进行注解,注解后只需声明相关参数如下图,重新编译后便可自动生成实体类。很方便。
常用注解:
@Id:主键 Long 型,可以通过@Id(autoincrement = true)设置自增长
@Property:设置一个非默认关系映射所对应的列名,默认是使用字段名,例如:@Property(nameInDb = "name")
@NotNull:设置数据库表当前列不能为空
@Transient:添加此标记后不会生成数据库表的列
@Entity
public class User {
@Id
private Long id;
private String name;
private String password;
完成实体类后Build->make module App 即可在Greendao包下生成Userdao文件。如下图
初始化Greendao:
初始化要在Application进行。新建MyApplication类继承Application。Kotlin代码如下:
class MyApploction : Application(){
companion object { //声明静态变量。
lateinit var daoSession : DaoSession
lateinit var context:Context
}
override fun onCreate() {
super.onCreate()
initDao()
context = applicationContext
}
fun initDao(){
val helper = DaoMaster.DevOpenHelper(this,"User")//创建的数据库名。
val db = helper.writableDb
daoSession = DaoMaster(db).newSession()
}
open fun getDaoInstant(): DaoSession { //用于获得对象
return daoSession
}
open fun getContext():Context{
return context
}
}
Greendao3增删改查:
新建UserDaoHelper类,在其中对增删改查进行封装,代码如下:
class UserDaoHelper{
fun insertUser(user: User){ //插入一条数据,该User类型为User实体类
MyApploction().getDaoInstant().userDao.insertOrReplace(user)
}
fun deleteUser(id:Long){ //根据ID删除一条数据
MyApploction().getDaoInstant().userDao.deleteByKey(id)
}
fun upDataUser(user: User){ //更新一条数据
MyApploction().getDaoInstant().userDao.update(user)
}
fun queryUser(name :String): List<User> { //按名字查找一条数据,并返回List
return MyApploction().getDaoInstant().userDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).list()
}
fun queryUserById(id: Long): List<User> { //按Id查找一条数据,并返回List
return MyApploction().getDaoInstant().userDao.queryBuilder().where(UserDao.Properties.Id.eq(id)).list()
}
}
更多的数据库功能可以根据Greendao3文档进行添加,在需要用到以上功能时直接调用即可。如上对增删改查方法进行调用即可。
如内容有问题欢迎大家批评与指出。请大家多多评论激励下博主。