buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}
在module的build.gradle文件中配置如下:
apply plugin: 'org.greenrobot.greendao'
android {
greendao {
schemaVersion 1 //数据库版本号
daoPackage ‘com.xxx.greendao.dao’//生成的工具类的包名
targetGenDir ‘src/main/Java’//生成的工具所在路径
}
}
导入依赖库
compile 'org.greenrobot:greendao:3.2.2'
compile 'net.zetetic:android-database-sqlcipher:3.5.6'// 这个是对数据库加密用的,对数据库加密,不是对数据库里面的内容加密。
greendao的配置就算完成了
在来看看注解:
@Entity -- 实体注解
public @interface Entity {
/**
* 在数据库中表的名称,默认为实体的类名
*/
String nameInDb() default "";
/**
* 定义索引,可以跨越多个列(默认为实体类成员变量的个数)
*/
Index[] indexes() default {};
/**
* 标记创建数据库表
* 若一个表映射多个实体类或者创建表外应的GreenDao,设置为false
*/
boolean createInDb() default true;
/**
* 告知GreenDao当前实体属于哪个schema
*/
String schema() default "default";
/**
* 实体活动状体标志位(默认为false)
* 若设置为true,实体有更新、删除和刷新方法
*/
boolean active() default false;
}
@NotNull
设置表中当前列的值不可为空
@Convert
指定自定义类型(@link PropertyConverter)
public @interface Convert {
/** 转换类*/
Class<? extends PropertyConverter> converter();
/**
* 在数据库中持久化的列
* 此受限于GreenDao所支持的类
*/
Class columnType();
}
@Id
主键 Long型,可以通过@Id(autoincrement = true)设置自增长。通过这个注解标记的字段必须是Long,数据库中表示它就是主键,并且默认是自增的。
public @interface Id {
/**
* 设置是否为自增长,默认为false
*/
boolean autoincrement() default false;
}
@Index
使用@Index作为一个属性来创建一个索引;定义多列索引(@link Entity#indexes())
public @interface Index {
/**
* 通过逗号间隔创建表的属性索引,例如 “propertyA,propertyB,propertyC”
* 若要指定排序, 需在列明以后添加 ASC(升序) 或者DESC(降序) , 例如 "propertyA DESC, propertyB ASC"
* 只有实体类中使用 {@link Entity#indexes()} 才可设置
*/
String value() default "";
/**
* 表的可选索引
* 默认为实体类中的成员变量
*/
String name() default "";
/**
* 是否为属性设置唯一属性,默认为false
*/
boolean unique() default false;
}
@Transient
添加次标记之后不会生成数据库表的列
@Unique
向数据库列添加了一个唯一的约束
@ToOne
定义与另一个实体(一个实体对象)的关系
public @interface ToOne {
/**
* 表中相关实体的属性名称
* 如果该参数不存在,则附加列会自动创建保存密钥
*/
String joinProperty() default "";
}
@ToMany 定义与多个实体对象的关系
public @interface ToMany {
/**
* 目标实体持有源实体的名称
* 此必须设置,否则有 {@link JoinProperty} or {@link JoinEntity} 指定
*/
String referencedJoinProperty() default "";
/**
* 将源表列索引->目标列
* 此必须设置,否则有 {@link JoinProperty} or {@link JoinEntity} 指定
*/
JoinProperty[] joinProperties() default {};
}
@Property
设置一个非默认关系映射所对应的列名,默认是的使用字段名 举例:@Property (nameInDb="name")
public @interface Property {
/**
* 默认是的使用字段名
*/
String nameInDb() default "";
}
@Keep
注解的代码段在GreenDao下次运行时保持不变
1.注解实体类:默认禁止修改此类
2.注解其他代码段,默认禁止修改注解的代码段
@JoinEntity
定义表连接关系
public @interface JoinEntity {
/** 添加的实体类 */
Class<?> entity();
/** 源表的列索引 */
String sourceProperty();
/** 连接表内拥有源实体的属性*/
String targetProperty();
}
@JoinProperty
定义名称和引用名称属性关系
public @interface JoinProperty {
/** 实体中的名称,对应于引用的名称 */
String name();
/** 引用的名称 */
String referencedName();
}
猛戳这里点击关注公众号⬇️ 即可了解我们更多: